in reply to Should calling 'exists' create a hash key?
This is called autovivification. To me, there are two types of autovivification, the ones that are useful, and the ones that are harmful (gotcha).
I have always seen the example you gave here as the harmful type, as it goes too far to guess your purpose and 99% of the time, nobody wants that free service.
But sometime it is useful, for example:
use strict; use warnings; my $a; $a->{"a"}{"b"}{"c"} = 1;
In this case, Perl will autovivify $a->{"a"} and $a->{"a"}{"b"}, and you don't need to initialize them explicitly. This is a clever idea, if I live on the six floor of 666 on street 888, obviously both street 888 and No. 666 exist. But it is ridiculous to assume that both No. 666 and street 888 exist, just because someone has asked whether "No.666 on street 888 has a six floor".
Also in this case:
my @a; a[100] = 2;
Perl will autovivify a[0] through a[99]. a[0] through a[99] come to existance without you explicitly doing so. This is different from languages like c or Java, in which you have to explicitly do it by allocate memory/new.
There are also other types of autovivifications.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Should this happen?
by Fletch (Bishop) on Sep 20, 2005 at 12:51 UTC | |
by pg (Canon) on Sep 20, 2005 at 13:21 UTC | |
by Fletch (Bishop) on Sep 20, 2005 at 13:57 UTC |