Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

autovivified hash key with foreach $x ( @{$h{a}} ) {}

by Danny (Pilgrim)
on May 17, 2024 at 17:25 UTC ( [id://11159506]=perlquestion: print w/replies, xml ) Need Help??

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

This
perl -we 'my %h; my @x = ( @{$h{a}} )'
gives 'Use of uninitialized value $h{"a"} in array dereference at -e line 1.'

which seems desirable, but

perl -wE 'my %h; foreach $x ( @{$h{a}} ) { say $x }; exists $h{a} and +print "true\n"'
creates the $h{a} key which seems kinda bad. Why is the foreach context treating ( @{$h{a}} ) differently?

Replies are listed 'Best First'.
Re: autovivified hash key with foreach $x ( @{$h{a}} ) {}
by Anonymous Monk on May 17, 2024 at 17:34 UTC
    Because the second is lvalue context, where autoviv happens.
      I see. Thanks.
Re: autovivified hash key with foreach $x ( @{$h{a}} ) {}. (Update x2)
by LanX (Saint) on May 17, 2024 at 17:45 UTC
    Probably because of the aliasing of $x

    Edit

    Here another kind of aliasing with the same "weirdness"

    $ perl -wE 'my %h; sub tst{ say @_ }; tst ( @{$h{a}} ); exists $h{a} a +nd print "true\n"' true

    I seem to remember we already had a similar discussion here not long ago...

    Update

    Now I remember, because of the aliasing, it's also an lvalue, i.e. it's potentially possible to assign to $x and consequently create the key.

    But the autovivification happens at the moment of aliasing, and not at the moment of assignment, because it's too complicated to implement.

    And yes, we had this discussion some month ago, I'll try to find the thread.

    Bottomline was that it's very complicated to cover all edge cases, and the devs want to keep the code simple.

    Update

    Compare unexpected modify hash in a distance with grep { $_ }

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery

      because of the aliasing, it's also an lvalue

      More precisely, because a modifiable alias is required.

      because it's too complicated to implement.

      I don't think so. We already do that for hash elements, and the same approach could be used to handle more complicated cases. It's a question of performance.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11159506]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-06-14 22:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.