Use strict is not very strict in Perl: 'my' in a conditional block

Strangely, "use strict" in Perl does not seem to correctly track improperly scoped variables if "my" is in a conditional block. The following throws no compilation-time errors in Perl 5.10.0 and 5.10.1, but its output shows that it is using a global variable:

use strict;
sub foo {
my $arg = shift;
my $var = 1 if $arg;
$var += 2;
return $var;
}
print foo(0).','.foo(0);

Output: 2,4

(The line "print foo(1).','.foo(1);" outputs "3,3", as expected.) Even more strangely, this only seems to happen if the condition follows the statement. The following code:

use strict;
sub foo {
my $arg = shift;
if($arg){ my $var = 1; }
$var += 2;
return $var;
}

throws the expected errors:

Global symbol "$var" requires explicit package name at - line 5.
Global symbol "$var" requires explicit package name at - line 6.
Execution of - aborted due to compilation errors.

This may have something to do with the presence of a statement block, but this throws no errors either:

use strict;
sub foo {
my $arg = shift;
do{ my $var = 1; } if $arg;
$var += 2;
return $var;
}

Popular Posts