Regex 逐行匹配文件

Regex 逐行匹配文件,regex,perl,for-loop,grep,pattern-matching,Regex,Perl,For Loop,Grep,Pattern Matching,$address\u数组[0]包含 $text_file = '/homedir/report'; open ( $DATA,$text_file ) || die "Error!"; #open the file @ICC2_array = <$DATA>; $total_line = scalar@ICC2_array; # total number of lines @address_array = split('\n',$address[6608]); # T

$address\u数组[0]
包含

$text_file = '/homedir/report';
open ( $DATA,$text_file ) || die "Error!";   #open the file
@ICC2_array = <$DATA>;

$total_line = scalar@ICC2_array;    # total number of lines

@address_array = split('\n',$address[6608]);  # The first content is what I want and it is correct, I have checked using print

LABEL2:
for ( $count=0; $count < $total_line; $count++ ) {

    if ( grep { $_ eq "$address_array[0]" } $ICC2_array[$count] ) {
        print "This address is found!\n";
        last LABEL2;
    }
    elsif ( $count == $total_line - 1 ) {  # if not found in all lines
        print "No matching is found for this address\n";
        last LABEL2;
    }
}
Startpoint: port/start/input_output (triggered by clock3)
Endpoint: port/end/input_output (rising edge-triggered)
$text\u文件中有一行是

Startpoint: port/start/input_output (triggered by clock3)

但是输出是“找不到与此地址匹配的”
,有人能指出我的错误吗?

@ICC2\u数组中的所有元素的末尾都将有新行字符

由于
$address\u数组[0]
是通过在
\n
上拆分数据创建的,因此保证不包含新行字符

以新行结尾的字符串永远不能等于不包含新行的字符串

我建议更换:

Startpoint: port/start/input_output (triggered by clock3)
@ICC2_数组=;
与:

chomp(@ICC2_数组=);

更新:我刚刚发现的另一个问题。在每次迭代中,您将增加两次
$count
。在循环控制代码(
$count++
)中递增,在
else
子句(
$count+=1
)中递增。因此,您可能只检查
@ICC2\u数组中的每个其他元素

我认为您的代码应该是这样的

核心模块
列表::Util
中的
any
操作符与
grep
类似,只是它在找到匹配项后立即停止搜索,因此平均速度应该是前者的两倍。
List::Util
的早期迭代不包含任何
any
,如果适用,您只需使用
grep

我已经从您的数组标识符中删除了
\u数组
,因为
@
表明它是一个数组,只是不需要的噪声

chomp(@ICC2_array = <$DATA>);
use List::Util'any';
我的$text_文件='/homedir/report';
我的@ICC2=do{

打开my$fh,'Perl不使用
/
进行注释。如果启用了
open
,如何检查失败?您必须始终以
use strict
use warnings'all'
开始每个Perl程序,并在代码中尽可能晚地使用
my
声明所有变量。
if(grep{$\ueq“$address\u array[0]”}$ICC2\u array[$count])
通常写入
if($ICC2\u array[$count]eq$address\u array[0])
地址中有什么?它是如何填充的?谢谢Dave Cross!我已经用你的suggestion@Kyle:那很好。但是请仔细看看博罗丁的答案,因为这显示了一种更好的编写代码的方法。@DaveCross:太宽宏大量了!@Borodin:我解决了眼前的问题。你退后一步ook更高层次地查看代码。更清楚的是,我尝试使用List::Util'any';any不是由module@Kyle:好的,那么您可以安装一个新的
List::Util
副本,也可以删除
use
语句并用
grep
替换
any
chomp(@ICC2_array = <$DATA>);
use List::Util 'any';


my $text_file = '/homedir/report';

my @ICC2 = do {
    open my $fh,'<', $text_file or die qq{Unable to open "$text_file" for input: $!};
    <$fh>;
};
chomp @ICC2;

my ( $address ) = split /\n/, $address[6608], 2;

if ( any { $_ eq $address } @ICC2 ) {
    print "This address is found\n"
}
else {
    print "No match is found for this address\n";
}