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";
答案 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
块之外使用$b
和sort
,因为它们是strict特殊的特殊包范围变量。