my $x;
$x->{foo};
print $x; # it's a hash!
and likewise
my $x;
$x->[0];
print $x; # it's an array!
In other words, Perl automatically turns any undefined lvalue into an an anonymous hash or array whenever you treat it like one. This is useful because it lets you do things like grouping input on multiple keys easily:
my $event;
while( <> ) {
chomp;
my ( $time, $lane, $factory, $event ) = split " ", $_;
$event->{ $factory }{ $lane }{ $time } = $event;
}
If Perl didn’t autovivify undefs, you’d have to write something like
my $event = {};
while( <> ) {
chomp;
my ( $time, $lane, $factory, $event ) = split " ", $_;
$event->{ $factory } = {}
if not exists $event->{ $factory };
$event->{ $factory }{ $lane } = {}
if not exists $event->{ $factory }{ $lane };
$event->{ $factory }{ $lane }{ $time } = $event;
}
Depending on how deep the structure is and whether any branches are optional depending on what conditions, you’d might end up spending a whole lot of time fiddling around to put the right things in the right places in the right succession. With autovivification, Perl just DWIMs.
But as you’ve seen, sometimes this is more than you were asking for. Because exists is only a function, not an operator, the lookup happens independently, and by the time exists sees the result, the deed has already happened.
You need to keep this in mind whenever you write multi-level lookups.
Makeshifts last the longest. |