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:
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'
}
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)?
I tried using eval (to no avail), and then s///e instead of m//, but I only got single interpolation:
$string =~ s/(\w+)_(\w+)_(\w+)/$patterns{$patternkey}/e;
print $string; # '$3$1$2'
If I put the replacement pattern in directly, though, it works fine:
$string =~ s/(\w+)_(\w+)_(\w+)/$3$1$2/;
print $string; # 'threeonetwo'
or
$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.