什么perl代码示例可能导致未定义的行为?

Eug*_*ash 14 perl

这些是我所知道的:

  1. my使用语句修饰符条件或循环结构(例如" my $x if ...")修改的" "语句的行为.
  2. 在同一语句中修改变量两次,例如 $i = $i++;
  3. sort() 在标量上下文中
  4. truncate(),当LENGTH大于文件的长度时
  5. 使用32位整数," 1 << 32"未定义.通过负位数移位也是不确定的.
  6. 非标量赋值给"状态"变量,例如state @a = (1..3).

Gra*_*ean 5

容易绊倒的一个是在迭代循环的过程中过早地突破循环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";
}
Run Code Online (Sandbox Code Playgroud)

输出:

The number 2 is called 'two'
Unable to find a name for 2
Run Code Online (Sandbox Code Playgroud)

这显然是一个愚蠢的例子,但这一点仍然存在 - 当each你通过哈希迭代时,你应该从不lastreturn不在循环中; 或者你应该keys %hash在每次搜索之前重置迭代器(with ).


dao*_*oad 4

这些只是修改正在迭代的结构主题的变体:

mapgrep以及sort代码引用修改要排序的项目列表的位置。

另一个问题sort是,代码引用不是幂等的(在计算机科学意义上)——对于任何给定的和 ,sort_func($a, $b)必须始终返回相同的值。$a$b