Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re^4: gotchas with hash element autovivification (lvalue)

by tye (Sage)
on Apr 03, 2012 at 14:06 UTC ( [id://963251]=note: print w/replies, xml ) Need Help??


in reply to Re^3: gotchas with hash element autovivification
in thread gotchas with hash element autovivification

Autovivification requires an lvalue "context". Just reading a value won't autovivify it. Both defined and exists are known to Perl to be read-only and so won't autovivify the last level of dereferencing.

Just testing a hash also won't autovivify (the last level). So I disagree with tobyink's "this would make the defined keyword kinda useless" because it hints that defined is somehow preventing autovivification. That's particularly problematic because that is actually a common misconception. Just testing defined or exists has no different behavior with regard to autovivification than directly testing the hash entry does.

And even when some function "would be passed the contents of the *value* slot of [an] entry", that isn't always enough to cause autovivification. Perl is (sometimes) smart enough to make the autovivification dependent on whether the function actually makes a modification.

my %hash; sub list { print join( ' ', sort keys %hash ), $/ } for( $hash{for} ) { # Don't do a single thing to $_ } list(); # 'for' entry autovivified unconditionally sub maybeset { for( $_[0] ) { $_ = $_[1] if 1 < @_ }; list() } maybeset( $hash{maybe} ); # no 'maybe', despite the for() in th +e sub maybeset( $hash{set}, 'hello' ); # now 'for set'

- tye        

Replies are listed 'Best First'.
Re^5: gotchas with hash element autovivification (lvalue)
by roboticus (Chancellor) on Apr 03, 2012 at 14:36 UTC

    tye:

    Thanks, that clears it up somewhat.

    Sometimes I wish perl were just a little less DWIMmy...or that it would dw*I*m! ;^D

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-04-19 02:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found