in reply to Re: Accidentally creating hash elements with grep { defined } on a hash slice
in thread Accidentally creating hash elements with grep { defined } on a hash slice

And what about $a, $b in sort? They are aliases also, but keys are not created.

Replies are listed 'Best First'.
Re^3: Accidentally creating hash elements with grep { defined } on a hash slice
by ikegami (Patriarch) on Nov 04, 2008 at 11:39 UTC

    I was just asking myself exactly that question. Turns out grep requires lvalues, but sort doesn't.

    >perl -MO=Concise -e"@b = grep f, @h{@a}" ... a <@> hslice lKM ->b ... >perl -MO=Concise -e"@b = sort @h{@a}" ... a <@> hslice lK ->b ...

    Notice the "M" for "Modifiable" in the former.

    So that begs the question: Why does grep require lvalues? The difference is:

    >perl -e"@a = grep { $_='!'; 0 } @h{qw(i j)};" >perl -e"@a = sort { $a='!'; 0 } @h{qw(i j)};" Modification of a read-only value attempted at -e line 1.

    But as far as I can tell, there is no good reason.

      Why does grep require lvalues?
      So you can suprise people with what this does:
      perl -e "@in = (1..5); @out = grep { $_++ } @in; print qq{@in}"
      But as far as I can tell, there is no good reason.
      Oh - a good reason? Sorry, haven't got one of them. Move along please, nothing to see here.

      --
      .sig : File not found.

        True, but it's a bad example since @in naturally returns lvalues.

        >perl -le" @in = (1..5); @out = sort { $a=$b='!'; 0 } @in; print qq{@i +n}" ! ! ! ! !

        Note the absence of the "M" flag.

        >perl -MO=Concise -le" @in = (1..5); @out = sort { $a=$b='!'; 0 } @in; + print qq{@in}" ... e <1> rv2av[t11] lK/1 ->f ...

        It will affect

        pp_pos - Adds lvalue magic pp_substr - Adds lvalue magic pp_vec - Adds lvalue magic pp_aelem - Extends array pp_aelemfast - Extends array pp_aslice - Extends array pp_helem - Extends hash pp_hslice - Extends hash pp_padsv - No effect as far as I can tell pp_rv2sv - ??? pp_rv2av - ??? pp_rv2gv - ???

      Thanks both for your replies. I understand the problem now :)