Reputation: 2613
I came across this piece of code (modified excerpt):
my $respMap;
my $respIdArray;
foreach my $respId (@$someList) {
push(@$respIdArray, $respId);
}
$respMap->{'ids'} = $respIdArray;
return $respMap;
Is there a reason to use autovivication in this case? Why not simply do
my $respMap;
my @respIdArray;
foreach my $respId (@$someList) {
push(@respIdArray, $respId);
}
$respMap->{'ids'} = \@respIdArray;
return $respMap;
Follow up: Could someone give me a good use case of autovivication?
Upvotes: 0
Views: 86
Reputation: 50637
Either way is correct; first one using array reference $respIdArray
, and second plain array @respIdArray
. You'll need array references when building complex data structures (check perldoc perlreftut
), but other than that it's up to you which one you'll choose.
Note that in both cases you're assigning array reference to $respMap->{'ids'}
, so examples are actually pretty similar.
And btw, autovivification is another thing and has to do with dynamic creation of data structures.
Upvotes: 1
Reputation: 14178
Autovivication is more useful when dealing with deep structures.
push( @{$hash{'key'}{$subkey}}, 'value' );
Upvotes: 1