Not directly related to your observation, but maybe still interesting in the wider context of autovivifying things...  While trying to get some third-party code to run under strict, I recently stumbled across the phenomenon that something like

if (%$href) { print "has elements" }

produces "Can't use an undefined value as a HASH reference" when $href is undefined (under strict, that is, works fine without strict), while

my @keys = keys %$href; my @vals = values %$href; while (my ($key, $val) = each %$href) { ... }

all work fine under strict, because they autovivify the hash.

(The former case - which could also be written as scalar %$href - is supposed to test if the referenced hash contains elements, with the special case that the hash doesn't exist at all being semantically equivalent to "has no elements").

The explanation based on aliases being created (implying lvalue-ness) only holds partially here: evaluating the hash in scalar context presumably does not create aliases (so the behaviour is "as expected"); values does create aliases (so that's as expected, too); but keys does not create aliases, at least not in a way that you could say

for (keys %$href) { $_ = "foo"; }

and have the keys in the hash be modified.  Still, it obviously autovivifies.


In reply to Re: Dereferencing undef as an array: Bug or WAD? (autovivification) by almut
in thread Dereferencing undef as an array: Bug or WAD? by BrowserUk

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.