是否存在Perl习语,它是在替换运算符中调用子例程的功能等价物?

时间:2010-04-01 00:29:05

标签: perl substitution subroutine idiomatic-perl

Perl允许......

$a = "fee";
$result = 1 + f($a) ; # invokes f with the argument $a

但不允许,或者说不做我想做的事......

s/((fee)|(fie)|(foe)|(foo))/f($1)/ ; # does not invoke f with the argument $1

期望的最终结果是一种实现正则表达式匹配的替换的方法。

我必须写

sub lala {
  my $haha = shift;
  return $haha . $haha;
}
my $a = "the giant says foe" ;
$a =~ m/((fee)|(fie)|(foe)|(foo))/;
my $result = lala($1);
$a =~ s/$1/$result/;
print "$a\n";

1 个答案:

答案 0 :(得分:12)

perldoc perlop。您需要指定e修饰符,以便评估替换部件。

#!/usr/bin/perl

use strict; use warnings;

my $x = "the giant says foe" ;
$x =~ s/(f(?:ee|ie|o[eo]))/lala($1)/e;

print "$x\n";

sub lala {
    my ($haha) = @_;
    return "$haha$haha";
}

输出:

C:\Temp> r
the giant says foefoe

顺便说一句,请避免在$a块之外使用$bsort,因为它们是strict特殊的特殊包范围变量。