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.
|