perl_fan has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

am writing a simple substitutes program where both parameter of substitute are stored in variables

#!/usr/local/bin/perl $string = '10 09'; $regex = '(\d+) (\d+)'; $replace = '$2 $1'; $string =~ s/$regex/$replace/; print "$string \n"; -----------------------
When i execute that, it gives me the following output
# ./test.cgi $2 $1

Replies are listed 'Best First'.
Re: regular expression problem
by jethro (Monsignor) on Aug 17, 2009 at 11:14 UTC

    Here is one solution:

    $string =~ s/$regex/eval "\"$replace\""/e;

    The problem with your method was that to get that to work it would have to do variable substitution twice, first to substitute $replace with '$2 $1', then a second variable substitution of $2 and $1. Using eval in connection with the e modifier basically does just this second variable substitution.

      Rather than use eval inside the replacement term you can use a double ee modifier (see the s operator in Regexp Quote Like Operators).

      $ perl -le ' > $str = q{10 09}; > $reg = q{(\d+) (\d+)}; > $rep = q{"$2 $1"}; > $str =~ s/$reg/$rep/ee; > print $str;' 09 10 $

      I hope this is of interest.

      Cheers,

      JohnGG

      Super cool
      
      Thanks you are a Hero
      
Re: regular expression problem
by biohisham (Priest) on Aug 17, 2009 at 12:18 UTC
    since you only have two variables, have you considered using an array and reversing the array ordering afterwards?

    Another thing, get accustomed to and stick around the strictures, and yeah, your code tags would have to be used to contain only your code and not the other body elements in your message (so please update your post accordingly), The code tags are figured to maintain the spaces and keep the code the way you organized it (preserving the lines relationship) so when used out of this context the display would really get distorted for each one of us (Read=> costing you vote-downs and grumbling-upons). So when you preview your message before creating it make sure:

    • It looks much like the other ones here in PM.
    • The code tags only contain code.
    • That you haven't employed the deprecated pre tags.
    • AND Read Posting on PerlMonks. (updated)
    Thanks :)

    #!/usr/local/bin/perl use strict; #get used to this use warnings; #and maybe this one too

    Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.
Re: regular expression problem
by Anonymous Monk on Aug 17, 2009 at 13:00 UTC