Limiting the scope to the if doesn't limit the lifetime of the value for destruction purposes (see if(my) scope), and if the outer scope already has an $x, you'll get a warning (easily fixed by using curlies or the other alternative I posted).
Agreed, except that the warning isn't always produced, depending on the surrounding scopes.
use strict;
use warnings;
my $x = "outermost x";
print "alternative 1\n";
if( e() ) {
my $x = f();
if( $x and g($x) ) {
print "inside the inner if \$x = $x\n";
}
print "after the inner if \$x = $x\n";
}
print "after the outer if \$x = $x\n";
print "\nalternative 2\n";
if( e() ) {
if( my $x = f() ) {
if( g($x) ) {
print "inside the inner if \$x = $x\n";
}
}
print "after the inner if \$x = $x\n";
}
print "after the outer if \$x = $x\n";
sub e {
return "sub e here";
}
sub f {
return "sub f here";
}
sub g {
return "sub g here";
}
__END__
alternative 1
inside the inner if $x = sub f here
after the inner if $x = sub f here
after the outer if $x = outermost x
alternative 2
inside the inner if $x = sub f here
after the inner if $x = outermost x
after the outer if $x = outermost x