in reply to What about if (my $var = foo()) { ... }
I'm confused. if BLOCK already creates a scope (in 5.8, at least)
>perl -c -Mstrict -we"if (my $r = f()) { g() } print($r);" Global symbol "$r" requires explicit package name at -e line 1. -e had compilation errors.
Note that the scope is around the entire statement, so any elsif clauses, "then" blocks, elsif blocks and else blocks will have access to the variable.
>perl -c -Mstrict -we"if (my $r = f1()) { g1() } elsif (my $r = f2()) +{ g2() }" "my" variable $result masks earlier declaration in same scope at -e li +ne 1. -e syntax OK
Update: Nevermind, I understand the question now. Like someone's already said, there's nothing stopping you from creating an explicit block.
>perl -c -Mstrict -we"{ my $r = f(); if ($r) { g() } } print($r);" Global symbol "$r" requires explicit package name at -e line 1. -e had compilation errors.
Caveat: last, next and redo will ignore the implicit block but will treat the explicit bare block as a loop.
>perl -le"sub f { 1 } for (1..2) { if (my $r = f()) { next } print ' +!' }" >perl -le"sub f { 1 } for (1..2) { { my $r = f(); if ($r) { next } } + print '!' }" ! !
|
|---|