Using $h{x} is sufficient to autovifiy a key/value pair if there is no key/value pair for the key 'x' in the hash %h.
In the first case you give, the key 'x' is added to the hash (the $h{x} bit does that) with the value undef. The %{...} then tries to dereference the undef and generates the error that you see.
The second case is equivalent to:
my $ref = undef;
keys %{$ref}; # or: keys %$ref;
which, somewhat surprisingly, is fine and is about the same as asking for the keys of an empty hash. I guess this is an element of DWIM coming into play - if you ask for the keys of a hash reference that you haven't gotten around to assigning any key/value pairs to yet, then a list of not keys (and no errors generated) is a pretty reasonable thing to do.
Perl is environmentally friendly - it saves trees
|