raybies:

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.


In reply to Re: gotchas with hash element autovivification by roboticus
in thread gotchas with hash element autovivification by raybies

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.