Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What perl code samples can lead to undefined behaviour?

Tags:

perl

These are the ones I'm aware of:

  1. The behaviour of a "my" statement modified with a statement modifier conditional or loop construct (e.g. "my $x if ...").
  2. Modifying a variable twice in the same statement, like $i = $i++;
  3. sort() in scalar context
  4. truncate(), when LENGTH is greater than the length of the file
  5. Using 32-bit integers, "1 << 32" is undefined. Shifting by a negative number of bits is also undefined.
  6. Non-scalar assignment to "state" variables, e.g. state @a = (1..3).
like image 847
Eugene Yarmash Avatar asked Feb 01 '10 12:02

Eugene Yarmash


2 Answers

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.

like image 63
Grant McLean Avatar answered Nov 15 '22 20:11

Grant McLean


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.

like image 30
daotoad Avatar answered Nov 15 '22 19:11

daotoad