in reply to gotchas with hash element autovivification
The gotcha is this: before exists or defined can operate on the hashref, perl has to navigate through the data structure to get to the hash reference, and it creates 'em as needed to get there. For example:
$ cat autovivify.pl #!/usr/bin/perl use strict; use warnings; use Data::Dump qw(dump); my %h = (A=>0); print "Foo" if defined $h{Apple}{Banana}{Seahorse}; print dump(\%h); $ perl autovivify.pl { A => 0, Apple => { Banana => {} } }
As I understand it[1], under the hood, the defined operator wants a scalar to test. So perl has to navigate through the hash to get *to* that scalar. In this case, it had to create a hash reference keyed from Apple, and inside that it needed to create another hash reference keyed from Banana. Now perl has a scalar value (the empty hash reference pointed to by Banana), and passes it to defined who's checking for the definedness of the Seahorse entry.
Notes:
[1] I've never spelunked in the perl source code, but I've studied compilers, and have an inkling of how things might go.
[2] I was surprised that there wasn't a Seahorse entryhash as well. Before testing it, I would've expected to see a Seahorse entry as well. But it's clearly not there!
...roboticus
When your only tool is a hammer, all problems look like your thumb.
Update: Fixed, ++ to tobyink for the catch.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: gotchas with hash element autovivification
by tobyink (Canon) on Apr 03, 2012 at 07:08 UTC | |
by roboticus (Chancellor) on Apr 03, 2012 at 10:06 UTC | |
by tye (Sage) on Apr 03, 2012 at 14:06 UTC | |
by roboticus (Chancellor) on Apr 03, 2012 at 14:36 UTC | |
by tobyink (Canon) on Apr 03, 2012 at 13:11 UTC |