为什么会出现以下代码警告? $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 $foo\n"; # same $foo } # now $foo goes out of scope print $foo; # error under 'use strict' => $foo is now out of scope
如果我们要在这个块中的其他地方声明我的$foo,包括在elsif(…)子句中,这将是同一范围内的重复声明,并且我们会收到一条警告消息.