You've pretty much got it. In Perl, all scalar containers (ie, a scalar variable, an element from an array, or an element from a hash) start out as "undef", which is different from C's notion of undefined. In C, undefined means "could be anything, but never anything useful". In Perl, undefined means "undef", the value. In numeric context, undef equates to zero, meaning if you treat undef as a number it acts like zero. Increment zero, and you get 1.

You can explicitly detect definedness with defined:

perl -E 'say "undefined" if ! defined($var);'

...or...

perl -E '$var = 1; say "defined" if defined($var);'

But numeric operations, including Boolean comparisons in numeric context cause undef to act like a "false" numeric value, which is to say, zero.

perl -E 'say "Hello" if undef == 0;'

...or...

my $var; # Currently $var is undef print $var + 5, "\n"; # 5 print ++$var, "\n"; # 1

That's really the less amazing thing. The more amazing thing is that you can implicitly create references to anonymous data structures. Consider this:

my %hash; $hash{foo} = { bar => 'baz' };

The { ... } curly braces around  bar => 'baz' act as explicit anonymous hash constructors, so the resulting structure looks like this:

%hash = ( foo => { # { is an anon-hash constructor bar => 'baz' } );

That's the boring explicit way. But this will create the exact same structure, without explicitly constructing the inner hashref:

my %hash; $hash{foo}{bar} = 'baz';

The { bar => 'baz'} hash ref was constructed implicitly.


Dave


In reply to Re^3: Initializing Hash Arrays in Perl by davido
in thread Initializing Hash Arrays in Perl by winterwind

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.