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

by
Jeremy Canfield |
Updated: June 15 2021
| Perl (Scripting) articles
Let's say fruit.txt contains the following.
apple
banana
orange
pineapple
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