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

How does one defer string substitution? Given the following code:
#!/usr/bin/perl my $s0 = "red apple"; my $s1 = $s0; print "s0 = $s0\n"; my $k = 0; my $pattern = qr/(.)ed/; $s0 =~ s/$pattern/++$k && "$1osy"/ge; print "$k change(s)\n"; print "s0 = $s0\n"; $k = 0; $pattern = qr/r(.)(.)/; my $replace = '$2ead'; $s1 =~ s/$pattern/++$k && $replace/ge; print "$k change(s)\n"; print "s1 = $s1\n";
How do I get $2 to be replaced correctly given that $replace is defined previous to the substitution? I was unsuccessful when using eval.

Ultimately, the value of $replace will be very long and complicated...

Thanks.

Replies are listed 'Best First'.
Re: defering substitution within double-quoted strings?
by sauoq (Abbot) on Sep 04, 2003 at 19:54 UTC
    my $replace = '"$2ead"'; $s1 =~ s/$pattern/++$k && $replace/gee;

    Note the two /e modifiers and the extra double quotes in $replace. The first eval will change the replacement to "$2ead" and the second eval does the double quote interpolation correctly.

    -sauoq
    "My two cents aren't worth a dime.";
    
      Thanks! This worked like a champ!
Re: defering substitution within double-quoted strings?
by chromatic (Archbishop) on Sep 04, 2003 at 20:31 UTC
    $pattern = qr/r(.)(.)/; my $replace = sub { "$_[0]ead" }; $s1 =~ s/$pattern/++$k && $replace->( $2 )/ge;
Re: defering substitution within double-quoted strings?
by hardburn (Abbot) on Sep 04, 2003 at 19:54 UTC

    I think eval is the only way to go about this. Can you show what you did when you tried it that way?

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated