Dear Monks,
Here is a simple program employing a simple regex match, which gives me the desired output:
use strict; use warnings; use 5.010; my $str = 'abcd'; my $pattern = '(ab)'; if ($str =~ $pattern) { my $repl = "--$1"; say '$repl: ', $repl; say 'old $str: ', $str; $str =~ s/$pattern/$repl/; say 'new $str: ', $str; } --output:-- $repl: --ab old $str: abcd new $str: --abcd
When I get the pattern from the command line, the result is the same:
my $str = 'abcd'; my $pattern = shift; if ($str =~ $pattern) { my $repl = "--$1"; say '$repl: ', $repl; say 'old $str: ', $str; $str =~ s/$pattern/$repl/; say 'new $str: ', $str; } --output:-- $ perl 2perl.pl '(ab)' $repl: --ab old $str: abcd new $str: --abcd
But if I also get the replacement from the command line, then there is a problem:
my $str = 'abcd'; my $pattern = shift; if ($str =~ $pattern) { my $repl = shift; say '$repl: ', $repl; say 'old $str: ', $str; $str =~ s/$pattern/$repl/; say 'new $str: ', $str; } --output:-- $ perl 2perl.pl '(ab)' '--$1' $repl: --$1 old $str: abcd new $str: --$1cd
I've tried using eval, but that doesn't work either:
my $str = 'abcd'; my $pattern = shift; if ($str =~ $pattern) { my $temp = shift; my $repl = eval $temp; say '$repl: ', $repl; say 'old $str: ', $str; $str =~ s/$pattern/$repl/; say 'new $str: ', $str; } --output:-- $ perl 2perl.pl '(ab)' '--$1' Use of uninitialized value $repl in say at 2perl.pl line 39. $repl: old $str: abcd Use of uninitialized value $repl in substitution (s///) at 2perl.pl li +ne 42. new $str: cd
How can I get perl to evaluate the replacement string in the context of my program? Note: I also tried the /e and /ee modifiers for s/// with no luck.
In reply to eval problem by 7stud
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |