Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying a pattern match involving a variable but this dang thing won't work. I have read (and tried) just about every suggestion on the net and would be very thankful for any help.
foreach $line (@file) { chomp($line); foreach $key (keys %hash) { $pattern = "s$key_val"; if($line =~ /$pattern/) { print "$line\n"; $line =~ s/$pattern/my_temp_var/; } } }
The idea is that if the hash key is "Fish", I want to find all lines containing "sFish_val" before replacing this string with "my_temp_var". But instead of printing the lines containing the sub-string defined in $pattern, the code prints every single line containing the letter 's'. Please Help!!! Thanks, Timothy

Replies are listed 'Best First'.
Re: Variables in regex pattern match give strange results.
by Zaxo (Archbishop) on Jan 24, 2002 at 10:54 UTC

    Perl is looking for the variable $key_val and finding it undefined. Change your pattern string to $pattern = "s${key}_val";. Also, in the regexes, it would be good to say /\Q$pattern\E/ just in case there are any metacharacters in there.

    After Compline,
    Zaxo

Re: Variables in regex pattern match give strange results.
by demerphq (Chancellor) on Jan 24, 2002 at 14:34 UTC