3 ms·
As it happens, hashes in Perl 5 autovivify by default (rather like defaultdicts in Python). In retrospect, this can seem rather surprising (if not off-putting)
by bonemachine 13y ago
As it happens, hashes in Perl 5 autovivify by default (rather like defaultdicts in Python). In retrospect, this can seem rather surprising (if not off-putting) to newcomers, so an argument can be made that a more conservative default behavior should have been chosen (like the more "hard-nosed" behavior of standard dicts in Python).
OTOH Perl people tend to like the way we can, for example, create histograms (and nested structures like graphs) a bit more fluently with autovivifying hashes, e.g.:
my %a;
for my $x (@x) { $a{$x}++ }
than if we always had to be saying
if (exists $a{$x}) {
$a{$x}++
}
else {
$a{$x} = 0
}
Or as Perlistas would be more prone to write (if forced to use a non-vivifying hash):
exists $a{$x} ? $a{$x}++ : { $a{$x} = 0 }
Or gosh, who knows:
$a{$x} = exists $a{$x} ? $a{$x}+1 : 0
Or to have sat around and waited for 10 years or so until Hash::Util was invented (after Perl 4's initial release), provided then you knew to look for it, and how), at which point you'd finally be able to say:
use Hash::Util 'unlock_keys';
But as it happens, when Perl 4 first came out, autovivification (and its cohort, promiscuous ducktyping) were chosen as the default behavior for many of the language's core constructs (not just hashes and arrays). It's just the way Perl rolls. Whether it's the "right" tradeoff to make or not, from a socio-engineering perspective, is an interesting question (and partially a matter of taste). But in general Perl has been pretty consistent in its approach to tradeoffs like these.