Perl:正则表达式模式中的条件代码执行

时间:2016-09-05 03:56:27

标签: regex perl pattern-matching

我知道Perl 5中所谓的实验(?{ ... })工具来执行代码作为此类print语句,设置全局变量。

但是,我需要:

  1. 引用(?{ ... })块内的匹配字符串;以及

  2. 取决于其值,执行一些任意代码

  3. 所需用法:

    $input =~ m/ (foo) 
                   (?{ if (defined (\1) { process(\1) } }) 
                  bar
              /x;
    

    注意:显然可能有很多替代方案可以实现相同的效果(TMTOWDI),但我现在只对上述风格感兴趣。因此,帖子。

1 个答案:

答案 0 :(得分:3)

这是一个例子。

perldoc perlre:

  

$^N包含与最近关闭的群组(子匹配)匹配的内容

<强> test_extended_re_code.pl

#!/usr/bin/env perl

use warnings;
use strict;

my @input = split /\n/, <<"END";
foo 123 bar
foo 456 bar
fo  789 bar
foo xyz bar
END

for my $input ( @input ) {
    $input =~ m/foo (\d+)(?{ process( $^N ) if $^N }) bar/;
}

sub process {
    my ($txt) = @_;
    print "Processing '$txt'\n";
}

<强>输出

Processing '123'
Processing '456'
相关问题