哪些 perl 代码示例会导致未定义的行为? [英] What perl code samples can lead to undefined behaviour?

查看:60
本文介绍了哪些 perl 代码示例会导致未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是我知道的:

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

推荐答案

在使用 each 遍历散列时过早地跳出循环是很容易被绊倒的.

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";
}

输出:

The number 2 is called 'two'
Unable to find a name for 2

这显然是一个愚蠢的例子,但重点仍然存在 - 当用 each 迭代哈希时,你不应该 lastreturn> 出圈;或者您应该在每次搜索之前重置迭代器(使用 keys %hash).

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.

这篇关于哪些 perl 代码示例会导致未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆