Why can't I declare a scalar variable inside an if statement? Does it have something to do with the scope of the variable?
Every block {...}
in Perl creates a new scope. This includes bare blocks, subroutine blocks, BEGIN blocks, control structure blocks, looping structure blocks, inline blocks (map/grep), eval blocks, and the bodies of statement modifier loops.
If a block has an initialization section, that section is considered within the scope of the following block.
if (my $x = some_sub()) {
# $x in scope here
}
# $x out of scope
In a statement modifier loop, the initialization section is not contained within the scope of the pseudo block:
$_ = 1 for my ($x, $y, $z);
# $x, $y, and $z are still in scope and each is set to 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With