G'day sectokia,

[Note: $a (and $b) are special variables; it's best to only use these for their intended purposes to avoid unexpected side effects; I've replaced $a with $h in the code below. Also, '//undef' is completely superfluous: if the LHS is undef, use undef instead. :-)]

See Autovivification and Arrow Notation in perlref.

Perl will autovivify as needed. It requires 'c' to check for 'd', so that key is autovivified. The 'd' key either exists and has a value or it doesn't exist and the value is undef: no autovivification is needed here.

You can use exists() to check for 'c'; only attempting to get a value for 'd' if 'c' exists. That can become unwieldy when there are multiple levels of keys; if you think autovivification is a problem, simply allow it then delete() afterwards.

The following code has examples which demonstrate these points.

$ perl -E ' use Data::Dump; { say "*** Autovivification"; my $h = { b => {} }; dd $h; my $f = $h->{b}{c}; say $f // "undefined"; dd $h; my $g = $h->{b}{c}{d}; say $g // "undefined"; dd $h; } { say "*** No autovivification"; my $h = { b => {} }; dd $h; my $f = $h->{b}{c}; say $f // "undefined"; dd $h; my $g = exists $h->{b}{c} ? $h->{b}{c}{d} : undef; say $g // "undefined"; dd $h; } { say "*** Autovivify then delete"; my $h = { b => {} }; dd $h; my $f = $h->{b}{c}{x}{y}{z}; say $f // "undefined"; dd $h; delete $h->{b}{c}; dd $h; } '

Output:

*** Autovivification { b => {} } undefined { b => {} } undefined { b => { c => {} } } *** No autovivification { b => {} } undefined { b => {} } undefined { b => {} } *** Autovivify then delete { b => {} } undefined { b => { c => { x => { y => {} } } } } { b => {} }

— Ken


In reply to Re: Arrow Operator Question by kcott
in thread Arrow Operator Question by sectokia

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.