2011-10-06 51 views
1

我認爲我的問題是非常類似於這個: How to use a variable in the replacement side of the Perl substitution operator? 區別在於,$ find和$ replace是一個散列的鍵和值我在用。如何通過使用鍵和值的散列來搜索和替換(替代)

while(($find,$replace) = each %hash){ 
$string_to_check =~ s/$find/$replace/e; 
} 

下面是在我的散列

鍵一對鍵 - 值對的一個示例:^/ABC(/.*)?$

值:www.abc.website。 COM $ 1

我在這裏得到的替代,但是$ 1將不通過(/.*)

隨着內容替換小號/// EE的不是s /// E,I得到:

Bareword found where operator expected at (eval 1) line 1, near "//xyz" 
(Missing operator before xyz?) 
Use of uninitialized value in substitution iterator at ./script line 46, <FH1> line 3470. 

...因此匹配部分被替換爲空字符串。

我假設,即

while(($find,$replace) = each %hash) 

不會做同樣作爲第一個答案線程中的其他問題,單引號我掛:

$replace='"foo $foo bar"'; 

是這樣對?

請原諒我的英語,謝謝你的幫助。 (我是Perl新手,一般編程)

回答

1

要評估存儲在$ replace中的$ 1,您需要使用eval。請注意,eval可能存在安全風險,因此請確保您控制%hash的內容。

while (my ($find, $replace) = each %hash) { 
    eval "\$string_to_check =~ s{$find}{$replace}"; 
} 
+0

就是這樣!感謝您的迴應。現在我需要找出爲什麼這個工作 - 我不知道'eval'。 – user982809

+0

http://perldoc.perl.org/functions/eval.html – AFresh1

+0

再次感謝!我在另一個線程中看到了eval(類似的問題),但我認爲它與s /// e相同。但它有所作爲。謝謝!經過2天的搜索,我知道了;) – user982809

-1

而不是$1在您替換使用\1。這是對第一個匹配組的反向引用。我認爲在這種情況下,你也可以完全放棄/e

+0

感謝您的回覆。 我將它改爲\ 1,但它不會用(/.*)的內容替換它 - 所以我現在得到abc.website.com \ 1 – user982809