Perl (Scripting) - Determine if file contains a string of data

Let's say fruit.txt contains the following.



To determine if fruit.txt does or does not contain a certain type of fruit, you can first store the fruit.txt in an array. In this example, the content of the fruit.txt file is stored in the @fruit array.

my $file = "fruit.txt";

# Open the file for reading
if (open FH, "<", $file) {

  # Load the content of the file into an array
  my @fruit = <IN>;

  # Close the file
  close IN;
else {
  print "failed to open $file \n";
  exit 1;


You can then use grep to determine if the @fruit array does or does not contain a certain type of fruit.

if (grep(/apple/, @fruit)) {
  print "fruit.txt contains 'apple' \n";

if (not grep(/peach/, @fruit)) {
  print "fruit.txt does not contains 'peach' \n"; 


Let's say you want to append fruit to fruit.txt only when fruit.txt does not contain the fruit in question.

if (not grep(/peach/, @fruit)) {
  print "fruit.txt does not contains 'peach' \n"; 

  # Open the file for appending
  open(OUT, ">>", $file) or die "Cannot open $file $! \n";

  # Append 'peach' to fruit.txt
  print OUT "peach \n";

  # close the file
  close OUT;


Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 97405 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |