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

I have the following code
$foo = "some sentence x"; $val = 1; while ($val < 5) { $foo =~ s/x/$val/; print "$val $foo\n"; $val++; }
I was expecting the substitution to be recompile everytime and new val is used. But not in thise case... why?
Thanks!

Replies are listed 'Best First'.
Re: substitution not recompile
by ikegami (Patriarch) on Mar 24, 2005 at 15:11 UTC

    It doesn't work because you removed the 'x' the first time around.

    $val = 1; while ($val < 5) { $foo = "some sentence x"; # Move this here $foo =~ s/x/$val/; print "$val $foo\n"; $val++; }

    or

    $foo = "some sentence x"; $val = 1; while ($val < 5) { my $foo = $foo; # Add this. $foo =~ s/x/$val/; print "$val $foo\n"; $val++; }
Re: substitution not recompile
by polettix (Vicar) on Mar 24, 2005 at 15:14 UTC
    The first time the substitution is executed you lose your x in $foo; next times, there's no x to substitute. You're probably looking for:
    $template = "some sentence x"; $val = 1; while ($val < 5) { $foo = $template; $foo =~ s/x/$val/; print "$val $foo\n"; $val++; }
    Flavio

    -- Don't fool yourself.
      Or maybe
      $template = "some sentence x"; for $val (1..4) { ($foo = $template) =~ s/x/$val/; print "$val $foo\n"; }


      Manav