in reply to Re: Reassigning $_ in loop doesn't stick
in thread Reassigning $_ in loop doesn't stick

This is totally wrong!

It's even documented. Just like @array returns its elements as aliases,

grep returns aliases into the original list

$ perl -MDevel::Peek -e' my $x; Dump $x; Dump $_ for $x; Dump grep 1, $x; Dump do { $x }; Dump map $_, $x; Dump sub { $x }->(); Dump eval { $x }; ' 2>&1 | grep 'SV =' SV = NULL(0x0) at 0x814ecdc # Address of $x SV = NULL(0x0) at 0x814ecdc # for aliases SV = NULL(0x0) at 0x814ecdc # grep aliases SV = NULL(0x0) at 0x814ecdc # do aliases SV = NULL(0x0) at 0x814ed9c # map copies SV = NULL(0x0) at 0x814f7f8 # sub copies SV = NULL(0x0) at 0x814ed9c # eval copies

Replies are listed 'Best First'.
Re^3: Reassigning $_ in loop doesn't stick
by Limbic~Region (Chancellor) on Jan 21, 2009 at 21:24 UTC
    ikegami,
    I sent you a /msg to this affect but since I found a conflict in map, I figured I would post for everyone's benefit. What version of perl is this and why doesn't it agree with the documentation (map aliases not copies)?

    Update: Confirmed with 5.10.0 that map aliases not copies
    I am guessing I am not understanding what you are saying.

    #!/usr/bin/perl use strict; use warnings; my @foo = 'a' .. 'd'; map { $_ = uc($_) } @foo; # look Mom, map in a void context print "@foo\n";

    Cheers - L~R

      Both grep and map operate on aliases in their block, as you show.

      What ikegami is showing is that grep will return aliases to the elements of the list it worked on while map will return copies (even if it hasn't modified them).

      The post to which you replied discusses whether map returns aliases or not. This is not related to whether map operates on an alias when executing the code block.

      What version of perl is this and why doesn't it agree with the documentation

      The docs (for 5.10.0) specify that grep returns aliases, but they are silent on whether map returns aliases or not.

      Confirmed with 5.10.0 that map aliases not copies

      Your snippet discards the return value of map without checking whether it's an alias or not.

        ikegami,
        I thought this might be what you meant on my way home from work. I just can't think of a good reason for it. It would be quite interesting if it worked in assignment (my $alias_to_foo = grep $_, $foo;) but it doesn't. So what benefit is there that the return value is an alias into the original list?

        Cheers - L~R