本文介绍了为什么在我重新声明 Perl foreach 控制变量时没有收到警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面代码中重新声明$i没有抛出警告?

Why is there no warning thrown for the redeclaration of $i in the following code?

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

for my $i (1..3) {
  my $i = 'DUMMY';
  print Dumper $i;
}

推荐答案

实际上,您只会收到相同范围内重新定义的警告.写作:

Actually, you only get warnings for redefinitions in the same scope. Writing:

use warnings;
my $i;
{
  my $i;
  # do something to the inner $i
}
# do something to the outer $i

完全有效.

我不确定 Perl 内部是否以这种方式处理它,但是您可以将 for 循环视为被解析为

is perfectly valid.

I am not sure if the Perl internals handle it this way, but you can think of your for loop as being parsed as

{
  my $i;
  for $i ( ... ) { ... }
  # the outer scope-block parens are important!
};

这篇关于为什么在我重新声明 Perl foreach 控制变量时没有收到警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 10:36