【问题标题】:How to get around the scope of the foreach loop in Perl如何绕过 Perl 中 foreach 循环的范围
【发布时间】:2013-10-01 02:07:03
【问题描述】:

所以我正在编写一些我的编译器真的不喜欢的代码。有两个数组,它们具有相同数量的索引。 @array 填充有0@otherarray 是按顺序填充的。在这个 foreach 循环中,它会跳过第一个值,因为它是在循环外填充的。 Count 在循环外也被声明为 1。

foreach (@array) {
    if ($count == 1) {
    } elsif($_ == 0 && @otherarray[$count-1] != undef) {
        $_ = $count;
        splice(@otherarray, @otherarray[$count - 1], 1);
    } else {
        $_ = $otherarray[ rand @otherarray ];
    }
$count++
}

它坚持我在这一行的数字 ne(!=) 中使用了未初始化的值,以及其他数组在 else/if/elsif 语句中的每一行:

elsif($_ == 0 && @otherarray[$count-1] != undef) 

我该如何解决这个问题?我确信这很明显,但我对 Perl 真的很陌生,所以我可能一开始就设置了错误?我已经声明了我的@otherarray

【问题讨论】:

  • 使用$而不是@来访问数组中的元素
  • 旁注,for my $count (0 .. $#array) 而不是 $count++
  • 顺便说一句,这是一种尝试洗牌的奇怪尝试吗?为什么不使用List::Util's shuffle
  • 仍然不太确定您要在这里做什么 - 您可以编辑您的代码/描述以澄清吗?

标签: arrays perl variables scope


【解决方案1】:

比较中的undef 未初始化。使用defined 而不是与undef 比较:

elsif($_ == 0 && defined($otherarray[$count-1]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2013-01-13
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多