Today I learned... #1: variable scoping in if-else blocks

This block of code is valid Perl:

if (my $var1 = calc1()) {
    say $var1;
} elsif (my $var2 = calc2()) {
    say "$var1, $var2";
}

As you can see, $var1, which is declared in the if clause, is visible inside the elsif clause too.

Perl never ceases to amaze me!

(Also appears in my blog)

3 Comments

Reuse var1 in elsif with strict on. :)

And wondering how can var1 be useful in elsif since it has falsy value.

where var1 is in elsif assignment (warnings will complain when having "my" in front of it)

Leave a comment

About karjala

user-pic I'm a Perl developer.