These are the ones I'm aware of:
my
" statement modified with a statement modifier conditional or loop construct (e.g. "my $x if ...
").$i = $i++;
sort()
in scalar contexttruncate()
, when LENGTH is greater than the length of the file1 << 32
" is undefined. Shifting by a negative number of bits is also undefined.state @a = (1..3)
.One that is easy to trip over is prematurely breaking out of a loop while iterating through a hash with each
.
#!/usr/bin/perl
use strict;
use warnings;
my %name_to_num = ( one => 1, two => 2, three => 3 );
find_name(2); # works the first time
find_name(2); # but fails this time
exit;
sub find_name {
my($target) = @_;
while( my($name, $num) = each %name_to_num ) {
if($num == $target) {
print "The number $target is called '$name'\n";
return;
}
}
print "Unable to find a name for $target\n";
}
Output:
The number 2 is called 'two'
Unable to find a name for 2
This is obviously a silly example, but the point still stands - when iterating through a hash with each
you should either never last
or return
out of the loop; or you should reset the iterator (with keys %hash
) before each search.
These are just variations on the theme of modifying a structure that is being iterated over:
map
, grep
and sort
where the code reference modifies the list of items to sort.
Another issue with sort
arises where the code reference is not idempotent (in the comp sci sense)--sort_func($a, $b)
must always return the same value for any given $a
and $b
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With