2010-04-01 28 views
1

的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"; 

回答

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

+1

謝謝!這樣可以節省分號鍵上的大量磨損。 – 2010-04-01 00:47:01

相關問題