数组 – 使用Perl将文件读入数组

我正在读取一个文件并将数据存储在名为@lines的数组中.然后,我使用for循环遍历这个数组,并且在我匹配某个值的循环内:
$find = "fever";

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

目前,我正在使用一个带有发热值的标量$find,而不是为每个过滤器执行重复的语句.

我可以传递一个数组进行比较,而不是一个标量关键字?

解决方法

如果您将文件读入列表,它将一次性完成所有操作
@array = <$fh>;  # Reads all lines into array

将其与读取到标量上下文中进行对比

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

一次读取整个文件可能是一个问题,但是你会得到这个想法.

然后你可以使用grep过滤你的数组.

@filteredArray = grep /fever/,@array;

然后,您可以使用标量获取已过滤行的计数,这会对数组的解释强制标量(即单值)上下文,在这种情况下返回计数.

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>

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...