开发者

What perl code samples can lead to undefined behaviour?

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. 开发者_如何学JAVA"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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜