1

I think my problem is pretty similar to this one: How to use a variable in the replacement side of the Perl substitution operator? The difference is, $find and $replace are the keys and values of a hash i am using.

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

Here's an example for one pair of key-value-pair in my hash

key: ^/abc(/.*)?$

value: www.abc.website.com$1

I get an substitution here, but the $1 won't be replaced by the content of (/.*)

With s///ee instead of s///e, i get:

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.

...and therefore the matching parts are replaced with an empty string.

I am assuming, that

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

won't do the same as the single quotes in the first answer to the other question in the thread i linked to:

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

Is that right?

Excuse my English and Thanks for your help in advance. (I am new to Perl and Programming in general.)

Community
  • 1
  • 1
user982809
  • 254
  • 4
  • 11

2 Answers2

1

To evaluate the $1 stored in $replace you will need to use eval. Note that eval can be a security risk, so make sure you control the contents of %hash.

while (my ($find, $replace) = each %hash) {
    eval "\$string_to_check =~ s{$find}{$replace}";
}
AFresh1
  • 406
  • 2
  • 5
  • That's it! Thanks for response. Now i need to find out why this does the job - i didn't know about 'eval'. – user982809 Oct 06 '11 at 20:44
  • Thanks again! I saw eval in the other thread (with the similar problem) but i thought it was the same as s///e. But it makes a difference. Thank you! After 2 days of searching, i got it ;) – user982809 Oct 06 '11 at 20:56
  • I've [recently learned](http://www.perlmonks.org/?node_id=930010) that there may well be a safer way than the `eval`. [String::Interpolate](http://search.cpan.org/~nobull/String-Interpolate-0.3/lib/String/Interpolate.pm)::[RE](http://search.cpan.org/~djerius/String-Interpolate-RE-0.03/lib/String/Interpolate/RE.pm) which I haven't used yet, but sounds nifty. – AFresh1 Oct 07 '11 at 03:23
-2

Instead of $1 in your replacement use \1. It's the backreference to the first matched group. I think in that case you can also drop /e entirely.

Cfreak
  • 19,191
  • 6
  • 49
  • 60
  • Thanks for your response. I changed it to \1 but it won't replace it with the content of (/.*) either - so i get abc.website.com\1 now – user982809 Oct 06 '11 at 19:37