in reply to Re^2: In place search and replace with a hash
in thread In place search and replace with a hash

c:\@Work\Perl\monks>perl -wMstrict -le "my %hash = ('$1' => 'oops', 'abc' => 'ok'); ;; 'abc' =~ m{ (abc) }xms; print qq{captured '$1'}; ;; print $hash{'$1'}; " captured 'abc' oops

Give a man a fish:   <%-(-(-(-<

Replies are listed 'Best First'.
Re^4: In place search and replace with a hash
by LanX (Saint) on Dec 28, 2014 at 02:59 UTC
    You missed the point. Imho RHS of s/// isn't evaluated w/o e flag.

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

        > ?

        Well AnoMonk said "single quotes ... prevent variable interpolation" that's misleading.

        update

        maybe clearer with an example

        DB<106> %h = (x => 0, '$1' => 1); => ("x", 0, "\$1", 1) DB<107> $s = 'axb' => "axb" DB<108> $s =~ s/(x)/'$1'/r; # no prevention => "a'x'b"

        single quotes on the RHS of s/// never prevent interpolation.

        Interpolation is the process to translate "$a $h{$b}" to $a . " " . $h{$b} at compile time.

        But the keys of a hash-fetch are not interpolated they are executed, otherwise something like $h{$a$b} wouldn't cause a syntax error.

        Cheers Rolf

        (addicted to the Perl Programming Language and ☆☆☆☆ :)

Re^4: In place search and replace with a hash
by hkates (Novice) on Dec 28, 2014 at 03:11 UTC
    Hi AnomalousMonk, thanks for your reply. I probably should have specified that I'm pretty new to perl. Could you comment at all at what your code does?

      The code example above was meant as a counter-example to what I understood LanX to be saying. Comments:

      my %hash = ('$1' => 'oops', 'abc' => 'ok'); # create a hash 'abc' =~ m{ (abc) }xms; # capture a sub-string to $1 print qq{captured '$1'}; # show what that string is print $hash{'$1'}; # show effect of single-quotes: no interpolation
      Had  $1 been used directly (as in $hash{ $1 }), the output would have been 'ok'. A more complete example:
      c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my %hash = ('$1' => 'oops', 'abc' => 'ok'); dd \%hash; ;; 'abc' =~ m{ (abc) }xms; print qq{captured '$1'}; ;; print 'single-quoted: ', $hash{'$1'}; print 'straight: ', $hash{ $1 }; " { "\$1" => "oops", "abc" => "ok" } captured 'abc' single-quoted: oops straight: ok


      Give a man a fish:   <%-(-(-(-<