Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

comment on

( [id://3333] : superdoc . print w/replies, xml ) Need Help??

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.


In reply to Double interpolation of captured substrings by bobf

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.