perl:`$ 1`如何在循环中表现?

时间:2017-06-14 15:05:22

标签: regex perl

我在perl中遇到了一些我不理解的行为:

>>> my @words = ('hello', 'there');
>>> $words[0] =~ /(el)/; print $1;
el
>>> $words[1] =~ /(el)/; print $1;
undef

但是循环:

>>> my @words = ('hello', 'there');
>>> foreach my $word (@words){
>>>    $word =~ /(el)/;
>>>    print "$1\n";
>>> }
el
el

这里发生了什么?如果在最新的正则表达式中它不匹配,我怎么能在循环中获得$ 1未定义,这样这样的东西就可以工作:

foreach my $word (@words) {
    $word =~ /(el)/;
    if ($1) {
        print "$word matched\n";
    } else {
        print "$word did not match\n";
    }
}

3 个答案:

答案 0 :(得分:1)

循环没有什么特别之处。

use strict;
use warnings;
use feature qw( say );

my @words = ('hello', 'there');
$words[0] =~ /(el)/; say $1 // "[undef]";
$words[1] =~ /(el)/; say $1 // "[undef]";

my @words = ('hello', 'there');
foreach my $word (@words){
    $word =~ /(el)/;
    say $1 // "[undef]";
}

输出:

el
el
el
el

$1和朋友只有在成功匹配时才会更改,因此您需要

for my $word (@words) {
    if ( $word =~ /el/ ) {
        print "$word matched\n";
    } else {
        print "$word did not match\n";
    }
}

答案 1 :(得分:0)

一种方法是完全避免使用特殊编号的变量,这些变量在运行之间不会被重置。相反,使用局部变量,并在每个循环的开头重置它:

use warnings;
use strict;

my @words = qw(
    one
    two
    three
);

for my $w (@words){
    my $store;

    if (($store = $w) =~ /(t)/){
        print "$store\n";
    }
    else {
        print "no match\n";
    }
}

输出:

two
three

答案 2 :(得分:0)

检查比赛的回报:

if ($word =~ /(el)/) {
  print "$word matched with [$1]\n";
} else {
  print "$word did not match\n";
}

我怀疑你的测试环境比你的脚本单独运行时要多一些,包括重置$1等等。