This is called autovivification. To me, there are two types of autovivification, the ones that are useful, and the ones that are harmful (gotcha).

I have always seen the example you gave here as the harmful type, as it goes too far to guess your purpose and 99% of the time, nobody wants that free service.

But sometime it is useful, for example:

use strict; use warnings; my $a; $a->{"a"}{"b"}{"c"} = 1;

In this case, Perl will autovivify $a->{"a"} and $a->{"a"}{"b"}, and you don't need to initialize them explicitly. This is a clever idea, if I live on the six floor of 666 on street 888, obviously both street 888 and No. 666 exist. But it is ridiculous to assume that both No. 666 and street 888 exist, just because someone has asked whether "No.666 on street 888 has a six floor".

Also in this case:

my @a; a[100] = 2;

Perl will autovivify a[0] through a[99]. a[0] through a[99] come to existance without you explicitly doing so. This is different from languages like c or Java, in which you have to explicitly do it by allocate memory/new.

There are also other types of autovivifications.


In reply to Re: Should this happen? by pg
in thread Should calling 'exists' create a hash key? by mje

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.