Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Deparse tells us this is what is being executed: </p> <pre><code>$find = 'start (.*) end'; $replace = "foo \cA bar"; $var = 'start middle end'; $var =~ s/$find/$replace/; </code></pre> <p>However, </p> <pre><code> /$find/foo \1 bar/ </code></pre> <p>Is interpreted as :</p> <pre><code>$var =~ s/$find/foo $1 bar/; </code></pre> <p>Unfortunately it appears there is no easy way to do this. </p> <p>You can do it with a string eval, but thats dangerous. </p> <p>The most sane solution that works for me was this: </p> <pre><code>$find = "start (.*) end"; $replace = 'foo \1 bar'; $var = "start middle end"; sub repl { my $find = shift; my $replace = shift; my $var = shift; # Capture first my @items = ( $var =~ $find ); $var =~ s/$find/$replace/; for( reverse 0 .. $#items ){ my $n = $_ + 1; # Many More Rules can go here, ie: \g matchers and \{ } $var =~ s/\\$n/${items[$_]}/g ; $var =~ s/\$$n/${items[$_]}/g ; } return $var; } print repl $find, $replace, $var; </code></pre> <h3>A rebuttal against the ee technique:</h3> <p>As I said in my answer, I avoid evals for a reason. </p> <pre><code>$find="start (.*) end"; $replace='do{ print "I am a dirty little hacker" while 1; "foo $1 bar" }'; $var = "start middle end"; $var =~ s/$find/$replace/ee; print "var: $var\n"; </code></pre> <p>this code does exactly what you think it does. </p> <p>If your substitution string is in a web application, you just opened the door to arbitrary code execution. </p> <p>Good Job. </p> <p>Also, it <strong>WON'T</strong> work with taints turned on for this very reason.</p> <pre><code>$find="start (.*) end"; $replace='"' . $ARGV[0] . '"'; $var = "start middle end"; $var =~ s/$find/$replace/ee; print "var: $var\n" $ perl /tmp/re.pl 'foo $1 bar' var: foo middle bar $ perl -T /tmp/re.pl 'foo $1 bar' Insecure dependency in eval while running with -T switch at /tmp/re.pl line 10. </code></pre> <p>However, the more careful technique is sane, safe, secure, <em>and</em> doesn't fail taint. ( Be assured tho, the string it emits is still tainted, so you don't lose any security. )</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload