2009-12-15 39 views
6

我想要做的是這樣的:那麼Perl:我可以在變量中存儲反向引用(而不是它們的值)嗎?

my $text = "The owls are not what they seem."; 
my $pattern = '(\s+)'; 
my $replacement = '-$1-'; 
$text =~ s/$pattern/$replacement/g; 

$文本應該是:The- -owls- -are- -not- -what- -they- -seem。

但它當然更像是: - $ 1 - $ 1 - $ - 1 - $ - 1 - $ - 1 - $ - 1 - scree。

我試過各種反向引用($ 1,\ 1,\ g {1},\ g1),他們都沒有 的工作。/e修飾符也不起作用。這可能嗎?

目的是改變物體內的一些文字,像這樣一行: $對象 - >替換(「()OO」,「$ 1AR」)

任何其他的想法這到底是怎麼做了什麼?

非常感謝。

+0

qr /(\ s +)/比'(\ s +)'更好' – 2009-12-15 18:44:09

回答

12

你可以EVAL,然後使用/ee擴大字符串:

my $text = "The owls are not what they seem."; 
my $pattern = '(\s+)'; 
my $replacement = q{"-$1-"}; 
$text =~ s/$pattern/$replacement/eeg; 

perldoc perlop

e評估右側的表達式。

ee評估右側爲一個字符串,然後EVAL結果

不過,我會

my $replacement = sub { "-$1-" }; 
$text =~ s/$pattern/$replacement->()/eg; 

感到更安全但是這一切都取決於你在做這個方面。

+0

ee = Eval然後展開變量。 – 2009-12-15 15:54:10

+2

我可以想到這個子。現在非常明顯。它完全適合。謝謝! – wuwuwu 2009-12-15 16:33:42

-3

$ text =〜s/$ pattern/- $ 1-/g;

+0

不,我不能直接提供' - $ 1-'部分這個。它在一個變量中: $ replacement =' - $ 1-'; $ text =〜s/$ pattern/$ replacement/g; – wuwuwu 2009-12-15 15:48:10

3

SinanÜnür的解決方案可以工作,但它仍然需要替換字符串在程序中的某個字面上。如果替換字符串來源於數據,你必須做一些事情有點票友:

sub dyn_replace { 
    my ($replace) = @_; 
    my @groups; 
    { 
    no strict 'refs'; 
    $groups[$_] = $$_ for 1 .. $#-;  # the size of @- tells us the number of capturing groups 
    } 
    $replace =~ s/\$(\d+)/$groups[$1]/g; 
    return $replace; 
} 

,然後使用它像

$text =~ s/$pattern/dyn_replace($replacement)/eg; 

注意,這也避免了eval,並允許使用修飾符像/ g。代碼取自this Perl Monks node,但我寫了該節點,所以它沒問題:)

+0

據我瞭解,這與SinanÜnür的子參考解決方案有些相似,除了它更復雜。 – wuwuwu 2009-12-15 18:41:15

+2

Sinan的解決方案需要$ replacement作爲subref內的文字字符串。 Mine允許它是任意的字符串值。 – Dan 2009-12-15 21:08:07

相關問題