in reply to evaluating $1 in a replace string

You're going to have to do an eval on the $rpl text in order to get it to evaluate the $1 within the regex.

Update Well, I thought doing a s///e on it would be the ticket, but apparently not. I'll keep working on it though. :-)

Update: The following code will work, you just have to change your placeholder from $1 to %s.

#!/usr/bin/perl -w use strict; my $find = 'proof(\S+)'; my $rpl = 'read%s'; my $text = 'proofing is proof it needed to be proofed'; if ($text =~ s/$find/ sprintf($rpl,$1) /e) { print "1st replacement made:\n\t$text\n"; }
Yes, it does place some limitations depending on how you are going to use it, but that's life. :-)

-caedes

Replies are listed 'Best First'.
Re: Re: evaluating $1 in a replace string
by dvergin (Monsignor) on Jul 08, 2002 at 05:53 UTC
    Regarding: Well, I thought doing a s//e on it would be the ticket, but apparently not.

    It takes a little extra work, but it is certainly do-able...

    #!/usr/bin/perl -w use strict; my $find = 'proof(\S+)'; my $rpl = '"read$1"'; my $text = 'proofing is proof it needed to be proofed'; if ($text =~ s/$find/$rpl/ee) { print "1st replacement made:\n\t$text\n"; }
    The double /ee is needed. The first /e sub's in the value of $rpl. The second /e evaluates that and DWIM's.

    The nested quotes are needed in defining $rpl because without the inner double-quotes, the second /e fails. Another way to do that bit (and this may help in understanding) would be: my $rpl  = '"read" . $1'; You have to get both the quoting and the /ee right for the thing to work as intended.

    HTH

    ------------------------------------------------------------
    "Perl is a mess and that's good because the
    problem space is also a mess.
    " - Larry Wall

      ObSecurity: Of course remember that this is an eval, so be sure to turn tainting on and watch where you're getting your input if what's winding up in $1 could come from an untrusted source (i.e. from a filthy user :).

      Triple sweetness! Now I understand. I think I'll use the following version, because it gives me the same end result (having a double-quoted replacement expression on the final evaluation) and allows me to use the replacement expression as it is given to me.
      #!/usr/bin/perl -w use strict; my $find = 'proof(\S+)'; my $rpl = 'read$1'; my $text = 'proofing is proof it needed to be proofed'; if ($text =~ s/$find/"\"$rpl\""/ee) { print "1st replacement made:\n\t$text\n"; }