2011-10-06 54 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