Arrays 使用Perl将文件读入数组
我当前正在读取一个文件,并将数据存储在名为Arrays 使用Perl将文件读入数组,arrays,perl,file-io,Arrays,Perl,File Io,我当前正在读取一个文件,并将数据存储在名为@lines的数组中。然后,我使用for循环遍历该数组,并在循环内匹配某些值: $find = "fever"; if ($_ =~ /$find/) { print "$_\n"; $number++; #@lines = #print ("there are : " . $number); } 目前,我正在使用标量,$find,其值为fever,而不是对每个过滤器执行重复语句 我可以传递一个数组来进行比较,而不是一
@lines
的数组中。然后,我使用for
循环遍历该数组,并在循环内匹配某些值:
$find = "fever";
if ($_ =~ /$find/) {
print "$_\n";
$number++;
#@lines =
#print ("there are : " . $number);
}
目前,我正在使用标量,$find
,其值为fever
,而不是对每个过滤器执行重复语句
我可以传递一个数组来进行比较,而不是一个标量关键字吗?如果将一个文件读入一个列表,它将立即获取所有内容
@array = <$fh>; # Reads all lines into array
然后,您可以使用scalar
获取过滤行的计数,这将强制对数组的解释使用scalar(即单值)上下文,在本例中返回计数
print scalar @filteredArray;
把这一切放在一起
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>
C:\temp>cat test.pl
严格使用;使用警告;#总是
我的@a=#从u_数据读取所有行__
我的@f=grep/fever/,@a;#只需要那些狂热的台词
打印“过滤线=”,标量@f;#打印我们得到的过滤行数
__资料__
abc
发烧
薯条
永远
111发烧111
abc
C:\temp>test.pl
过滤线=2
C:\temp>
如果您有Perl 5.10或更高版本,您可以使用智能匹配(~
):
使用。它将文件加载到一个数组中,您可以使用数组操作对该数组进行操作。当您解开文件时,其组件将保存回文件中。您也可以使用该模块,这很方便
use strict;
use warnings;
use File::Slurp 'read_file';
my $fname = shift or die 'filename!';
my @lines = grep /fever/, read_file $fname; # grep with regular expression
print @lines;
如果您是Perl新手,请查看map
和grep
操作符,它们对于处理列表非常方便
另外,看看这个实用程序,它是
find
/grep
的绝佳替代品。(事实上,这是一个更好的选择。)如果它阐明了如何获取任意文件的文件句柄,例如如果您在$filename
中有文件名,那么这将是一个更好的答案。顺便说一句,数据对我来说是一个新的数据,但我从来都只是一个随意的Perl用户。
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>
my @patterns = (qr/foo/, qr/bar/);
if ($line ~~ @patterns) {
print "matched\n";
}
use strict;
use warnings;
use File::Slurp 'read_file';
my $fname = shift or die 'filename!';
my @lines = grep /fever/, read_file $fname; # grep with regular expression
print @lines;