# False, key doesn't exist, doesn't print and doesn't create anything at that key location
my $h;
say "foo" if $h->{foo};
# Creates an empty hash ref at $h->{foo}, so $h->{foo} now evaluates to true in boolean context.
$h->{foo}{bar}
# True, prints "foo";
say "foo" if $h->{foo}
# creates empty hash refs at bar and baz.
say "what does this do?" if $h->{foo}{bar}{baz}{quux};
Works with array refs as well.Personally, I find once you understand it, it's fairly easy to guard against (even if it requires more code. e.g. say "foo" if $h->{foo} and $h->{foo}{bar}; # Assuming we know $h is a hash ref already.
Edit: Typo and code block formatting
no autovivification;
http://search.cpan.org/~vpit/autovivification/lib/autovivifi...One of the things that's always impressed me the most about Perl is the degree to which modules can play with the language. Modules can add control structures (Try::Tiny), introduce new metaprogramming syntax (Moose), add operator overloading (overload)... it's very flexible.
That's exactly the point of the article, btw.
> Modules can add control structures (Try::Tiny), introduce new metaprogramming syntax (Moose), add operator overloading (overload)... it's very flexible.
Technically they add functions, and the language allows you to use imported functions as control structures. This isn't so much to correct you as to clarify it for less familiar readers.
if (exists $foo->{bar}){ .. will not run .. }
if ($foo->{bar}) {...}
if (exists $foo->{bar}){ .. will run .. }
if (exists $foo->{bar}){ .. will not run .. } if ($foo->{bar}->{baz}) {...} if (exists $foo->{bar}){ .. will run .. }
As an infrequent perl programmer[1], I'm curious about the bug. Googling tells me that perl if($foo->{bar}) will always pass, which is pretty goofy to me. Was it something like that?
[1] Well really, a bad perl programmer. I've occasional had to make minor edits to legacy perl. I don't write perl. And, as the mistake in this post shows, that's probably a good thing :)