7stud has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: eval problem
by ikegami (Patriarch) on Dec 03, 2009 at 20:17 UTC | |
by 7stud (Deacon) on Dec 03, 2009 at 21:01 UTC | |
by ikegami (Patriarch) on Dec 03, 2009 at 21:31 UTC | |
by 7stud (Deacon) on Dec 04, 2009 at 01:25 UTC | |
by ikegami (Patriarch) on Dec 04, 2009 at 02:18 UTC | |
by ikegami (Patriarch) on Dec 04, 2009 at 04:57 UTC | |
|
Re: eval problem
by AnomalousMonk (Archbishop) on Dec 04, 2009 at 01:52 UTC | |
|
Re: eval problem
by bv (Friar) on Dec 04, 2009 at 04:25 UTC | |
|
Re: eval problem
by 7stud (Deacon) on Dec 04, 2009 at 06:29 UTC | |
by ikegami (Patriarch) on Dec 04, 2009 at 07:27 UTC |