Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a scalar inside an if statement?

Tags:

perl

Why can't I declare a scalar variable inside an if statement? Does it have something to do with the scope of the variable?

like image 445
ianc1215 Avatar asked Dec 01 '22 02:12

ianc1215


1 Answers

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
like image 64
Eric Strom Avatar answered Dec 05 '22 00:12

Eric Strom