文件读入使用Perl数组 [英] Read a file into an array using Perl
问题描述
我目前正在读的文件,并在名为阵列中存储数据 @lines
。然后,我遍历这个数组用为
循环,我对某些值相匹配的循环中:
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?
推荐答案
如果你读一个文件到列表,它会立刻一切
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.
然后你可以使用的grep
来过滤阵列。
Then you can use grep
to filter your array.
@filteredArray = grep /fever/, @array;
然后你就可以得到使用标
,迫使标过滤的行数(即单个值)的阵列间pretation的背景下,在这种情况下,返回的计数。
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>
这篇关于文件读入使用Perl数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!