Read a file into an array using Perl Read a file into an array using Perl arrays arrays

Read a file into an array using Perl


If you read a file into a list it will take everything at once

@array = <$fh>;  # Reads all lines into array

Contrast this with reading into a scalar context

$singleLine = <$fh>;  # Reads just one line

Reading the whole file at once can be a problem, but you get the idea.

Then you can use grep to filter your array.

@filteredArray = grep /fever/, @array;

Then you can get the count of filtered lines using scalar, which forces scalar (that is, single value) context on the interpretation of the array, in this case returning a count.

print scalar @filteredArray;

Putting it all together...

C:\temp>cat test.pluse strict; use warnings;  # alwaysmy @a=<DATA>;  # Read all lines from __DATA__my @f = grep /fever/, @a;  # Get just the fevered linesprint "Filtered lines = ", scalar @f;  # Print how many filtered lines we got__DATA__abcfeveredfrierforever111fever111abcC:\temp>test.plFiltered lines = 2C:\temp>


If you have Perl 5.10 or later, you can use smart matching (~~) :

my @patterns = (qr/foo/, qr/bar/);if ($line ~~ @patterns) {    print "matched\n";  }


Use Tie::File. It loads the file into an array, which you can manipulate using array operations. When you untie the file, its components will be saved back in the file.