perl script to search n place a pattern

hi,
i have one file as t1.txt as below
hi
hello
welcome

i want perl script to search for the pattern "abcd" in the file.
if the pattern doesn't exist, i want to insert that pattern at the end of the same file t1.txt
my o/p should be

hi
hllo
welcome
abcd

thank you

anything you tried so far ?

Quick code, but shell script

$ if [ grep -q 'abcd' a.txt ]; then 
<DO SOMETHING / LEAVE IT BLANK>
else
  echo "abcd" >> a.txt
fi
  • in perl code, you would read a file in an array
  • Use perl - grep function to check if abcd exist?
  • if yes do what even you want
  • if it does not, open another file in write mode add "abcd" to end of old array ( $Array[-1] )
  • print it on new file handler
  • move new_file -> old_file
 
$ cat test
hi
hello
welcome
 
$ perl -lane 'print $_; $a=1 if $_=~/abcd/; END{if ($a ne 1) {print "abcd"}}' test
hi
hello
welcome
abcd
 
$ echo "abcd" >> test
 
$ cat test
hi
hello
welcome
abcd
 
$ perl -lane 'print $_; $a=1 if $_=~/abcd/; END{if ($a ne 1) {print "abcd"}}' test
hi
hello
welcome
abcd