Read a file into an array using Perl

后端 未结 4 1168
情书的邮戳
情书的邮戳 2020-12-31 06:25

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

4条回答
  •  借酒劲吻你
    2020-12-31 07:25

    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=;  # 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>
    

提交回复
热议问题