Because of autovivification-related bugs, I got into the habit of using defined instead of exists to determine whether a hash contains a certain key.
Back up one second there. exists exists in Perl's vocabulary for the purpose of determining if a hash element exists. defined doesn't tell you whether or not it exists, it tells you whether or not it has a value set.
The autovivication problem doesn't occur when you do this:
print "Exists!\n" if exists $hash{somekey};
It occurs when you do something like this:
my %hash = ( Key1 => { john => 1, pete => 2 }, Key2 => { frank => 3, howard => 4 } ); print "ted Exists!\n" if exists $hash{Key7}{ted}; print "Key7 now exists!\n" if exists $hash{Key7};
The difference is that in order to test for the existance of ted as an element referenced by $hash{Key7} Perl has to autovivify Key7. That is a big difference. The moral of the story is to always check for the existance of the higher level (if you cannot assume it exists) before checking for the existance of the lower level. But that's no reason to resort to using defined to do exists job, and in fact, using defined in this sort of context isn't going to prevent autovivication since testing for ted's value still requires that Key7 spring into existance silently.
To that point, the "autovivication bugs" issue is not a bug in exists, it's a type of bug that programmers encounter by not understanding how autovivication works.
Dave
In reply to Re^2: need explanation of @foo{@bar} = (); (hash slice)
by davido
in thread need explanation of @foo{@bar} = (); (hash slice)
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |