Why does the following code warn? $match is scoped to the if block and not the containing while block.
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.
As expected, it complains that $match is not defined at line 18, but it also complains about the redeclaration of $match in the if blocks. Version is slightly out of date but not horribly so; and it’s the most recent Strawberry version:
This is perl 5, version 12, subversion 3 (v5.12.3) built for MSWin32-x86-multi-thread
The scope of the first
$matchdeclaration is the entireif-elsif-elseblock. That lets you do things like this:If we were to declare
my $fooanywhere else in this block, including in theelsif (...)clause, that would be a duplicate declaration in the same scope, and we’d get a warning message.