bobf has asked for the wisdom of the Perl Monks concerning the following question:
Oh wise ones,
I am trying to write a function that returns a string that is assembled from a regex, but the order that the captured substrings are assembled in is determined by one of the passed arguments. Here is an overly simplified example of what I'm trying to do:
How can I get the function to return a double-interpolated value (once to get the hash value, then again to get the captured substrings)?my $newstring = munge_string( 'one_two_three', '312' ); sub munge_string { my ( $string, $patternkey ) = @_; # patterns can also be 'text$1$2$3', etc my %patterns = ( 123 => '$1$2$3', 312 => '$3$1$2' ); # in reality the regex is also dynamic (based on $patternkey) $string =~ m/(\w+)_(\w+)_(\w+)/; return $patterns{$patternkey}; # want 'threeonetwo', got '$3$1$2' }
I tried using eval (to no avail), and then s///e instead of m//, but I only got single interpolation:
If I put the replacement pattern in directly, though, it works fine:$string =~ s/(\w+)_(\w+)_(\w+)/$patterns{$patternkey}/e; print $string; # '$3$1$2'
or$string =~ s/(\w+)_(\w+)_(\w+)/$3$1$2/; print $string; # 'threeonetwo'
$string =~ s/(\w+)_(\w+)_(\w+)/join( '', $3, $1, $2 )/e; print $string; # 'threeonetwo'
Is there a way to do this cleanly, or am I going about this the wrong way? Thanks in advance.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Double interpolation of captured substrings
by gaal (Parson) on Nov 17, 2004 at 09:59 UTC | |
Re: Double interpolation of captured substrings
by Arunbear (Prior) on Nov 17, 2004 at 10:05 UTC | |
Re: Double interpolation of captured substrings
by ihb (Deacon) on Nov 17, 2004 at 10:21 UTC | |
Re: Double interpolation of captured substrings
by BrowserUk (Patriarch) on Nov 17, 2004 at 10:26 UTC | |
by Fletch (Bishop) on Nov 17, 2004 at 16:59 UTC | |
Re: Double interpolation of captured substrings
by TedPride (Priest) on Nov 17, 2004 at 10:26 UTC | |
Re: Double interpolation of captured substrings
by bobf (Monsignor) on Nov 17, 2004 at 23:26 UTC |
Back to
Seekers of Perl Wisdom