3 ms·
You don't have to define 'self' in Perl code, but you should. You don't have to check if a key in a dict exists, but you should. Not doing these things, and the
by peterwwillis 8y ago
You don't have to define 'self' in Perl code, but you should. You don't have to check if a key in a dict exists, but you should. Not doing these things, and the crappy code that results, are part of why people make fun of Perl.
$ cat > foo.pl <<EOF
use strict; use warnings;
{ package Foo;
sub new { my $class = shift; bless {}, $class }
sub method {
my $self = shift;
$self->{"hash"} = { "thng1" => shift };
my $key = $self->{"hash"}->{"thing1"};
$self->increment($key);
}
sub increment { $_[1] + 1 }
}
my $count = Foo->new()->method(33);
print "count: $count\n";
EOF
$ perl foo.pl && echo "Program succeeded"
Use of uninitialized value $_[1] in addition (+) at foo.pl line 12.
count: 1
Program succeeded
The debugger is telling us about an uninitialized variable in Foo::increment(), but the bug is really a missing dict key in Foo::method() due to a typo. We never checked if it existed, Perl didn't care either way, and the program didn't even fail. In code that's more than a page long, good luck spotting that...