The minimal form is actually:

my $x; $x->{foo}; print $x; # it's a hash!

and likewise

my $x; $x->[0]; print $x; # it's an array!

In other words, Perl automatically turns any undefined lvalue into an an anonymous hash or array whenever you treat it like one. This is useful because it lets you do things like grouping input on multiple keys easily:

my $event; while( <> ) { chomp; my ( $time, $lane, $factory, $event ) = split " ", $_; $event->{ $factory }{ $lane }{ $time } = $event; }

If Perl didn’t autovivify undefs, you’d have to write something like

my $event = {}; while( <> ) { chomp; my ( $time, $lane, $factory, $event ) = split " ", $_; $event->{ $factory } = {} if not exists $event->{ $factory }; $event->{ $factory }{ $lane } = {} if not exists $event->{ $factory }{ $lane }; $event->{ $factory }{ $lane }{ $time } = $event; }

Depending on how deep the structure is and whether any branches are optional depending on what conditions, you’d might end up spending a whole lot of time fiddling around to put the right things in the right places in the right succession. With autovivification, Perl just DWIMs.

But as you’ve seen, sometimes this is more than you were asking for. Because exists is only a function, not an operator, the lookup happens independently, and by the time exists sees the result, the deed has already happened.

You need to keep this in mind whenever you write multi-level lookups.

Makeshifts last the longest.


In reply to Re: Should calling 'exists' create a hash key? by Aristotle
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.