加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 为什么在if / elsif树中得到同一范围警告中的重复声明?

发布时间:2020-12-15 22:03:44 所属栏目:大数据 来源:网络整理
导读:为什么会出现以下代码警告? $match被限定为if块,而不是包含while块. use strict;use warnings;use 5.012;use IO::All;my $file = io($ARGV[0])-tie;my $regex = qr//;while (my $line = $file) { if (my ($match) = $line =~ $regex) { ... } elsif (my ($m
为什么会出现以下代码警告? $match被限定为if块,而不是包含while块.
use strict;
use warnings;
use 5.012;

use IO::All;

my $file = io($ARGV[0])->tie;
my $regex = qr//;

while (my $line = <$file>) {
  if (my ($match) = $line =~ $regex) {
    ...
  }
  elsif (my ($match) = $line =~ $regex) {
    ...
  }
  say $match;
}
C:&;perl testwarn.pl test.log
"my" variable $match masks earlier declaration in same scope at testwarn.pl line 15.
Global symbol "$match" requires explicit package name at testwarn.pl line 18.
Execution of testwarn.pl aborted due to compilation errors.

正如预期的那样,它抱怨$match没有在第18行定义,但是它也抱怨if块中$match的重新声明.版本略有过时,但不太可怕这是最新的草莓版本:

This is perl 5,version 12,subversion 3 (v5.12.3) built for MSWin32-x86-multi-thread

解决方法

第一个$match声明的范围是整个if-elsif-else块.这可以让你做这样的事情:
if ( (my $foo = some_value()) < some_other_value() ) {
    do_something();
} elsif ($foo < yet_another_value()) { # same $foo as in the if() above
    do_something_else();
} else {
    warn "$foo was $foon";   # same $foo
}   # now $foo goes out of scope
print $foo;   # error under 'use strict' => $foo is now out of scope

如果我们要在这个块中的其他地方声明我的$foo,包括在elsif(…)子句中,这将是同一范围内的重复声明,并且我们会收到一条警告消息.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读