范围运算符在 perl 中的用法



我有以下代码,尤其是 if 块中的条件以及如何获取 id,以阅读文件中的以下文本并显示 id,如下所述:

使用范围运算符 ..:

use strict;
use warnings;
use autodie;
#open my $fh, '<', 'sha.log';
my $fh = *DATA;
my @work_items;
while (<$fh>) {
    if ( my $range = /Work items:/ ... !/^s*(d+) (d+)/ ) {
        push @work_items, $1 if $range > 1 && $range !~ /E/;
    }
}
print "@work_itemsn";

文件中的文本

__DATA__
Change sets:
  (0345) ---$User1 "test12"
    Component: (0465) "textfiles1"
    Modified: 14-Sep-2014 02:17 PM
    Changes:
      ---c- (0574) /<unresolved>/sha.txt
    Work items:
      (0466) 90516 "test defect
      (0467) 90517 "test defect
Change sets:
  (0345) ---$User1 "test12"
    Component: (0465) "textfiles1"
    Modified: 14-Sep-2014 02:17 PM
    Changes:
      ---c- (0574) /<unresolved>/sha.txt
    Work items:
      (0468) 90518 "test defect

输出:

90516 90517

90518

问题:范围运算符与两个点一起使用,为什么在这里与 3 个点一起使用?

首先,它不是真正的范围运算符;在标量上下文中使用时,它被称为触发器运算符。像所有符号运算符一样,它以perlop记录。

...几乎和..一样。当使用...而不是..时,结束条件不会与开始条件在同一刀路进行测试。

$ perl -E'for(qw( a b a c a d a )) { say if $_ eq "a" .. $_ eq "a"; }'
a     # Start and stop at the first 'a'
a     # Start and stop at the second 'a'
a     # Start and stop at the third 'a'
a     # Start and stop at the fourth 'a'
$ perl -E'for(qw( a b a c a d a )) { say if $_ eq "a" ... $_ eq "a"; }'
a     # Start at the first 'a'
b
a     # Stop at the second 'a'
a     # Start at the third 'a'
d
a     # Stop at the fourth 'a'

每 http://perldoc.perl.org/perlop.html#Range-Operators:

如果您不希望它在下一次评估之前测试正确的操作数,例如在 sed 中,只需使用三个点 ("...") 而不是两个。在所有其他方面,"..."行为就像".."一样。

所以,这个:

/Work items:/ ... !/^s*(d+) (d+)/

表示"从与/Work items:/匹配的行到与/^s*(d+) (d+)/不匹配的下一行",而这:

/Work items:/ .. !/^s*(d+) (d+)/

意味着"从与/Work items:/匹配的行到不匹配/^s*(d+) (d+)/行"(即使它是同一行)。

最新更新