Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file into an array using Perl

I am currently reading a file and storing the data in an array named @lines. Then, I loop through this array using a for loop and inside the loop I match on certain values:

$find = "fever";

if ($_ =~ /$find/) {
    print "$_\n";
    $number++;
    #@lines =
    #print ("there are : " . $number);
}

At the moment, I am using a scalar, $find, with a value of fever instead of performing the repetitive statements for each filter.

Can I pass an array for comparison instead of a scalar keyword?

like image 698
alex Avatar asked May 10 '11 09:05

alex


People also ask

How do I read an array file in Perl?

readline in LIST context. In this case, after opening the file we read from the $fh filehandle into an array variable: my @rows = <$fh>;. In this case Perl will read in the content of the whole file in one step. Each row in the file will be one of the elements of the array.

How do I store a file in an array in Perl?

Just reading the file into an array, one line per element, is trivial: open my $handle, '<', $path_to_file; chomp(my @lines = <$handle>); close $handle; Now the lines of the file are in the array @lines .


2 Answers

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.pl
use strict; use warnings;  # always

my @a=<DATA>;  # Read all lines from __DATA__

my @f = grep /fever/, @a;  # Get just the fevered lines

print "Filtered lines = ", scalar @f;  # Print how many filtered lines we got

__DATA__
abc
fevered
frier
forever
111fever111
abc

C:\temp>test.pl
Filtered lines = 2
C:\temp>
like image 105
Ed Guiness Avatar answered Sep 18 '22 17:09

Ed Guiness


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";  
}
like image 34
Eugene Yarmash Avatar answered Sep 17 '22 17:09

Eugene Yarmash