There is a way you can avoid declaring $bar once and assining it an other time:
use strict; my $foo = 1; { my $bar = do { if ($foo) { "true"; } }; print $bar; }
You still need a pair of braces around the whole construct. If you want $bar to be local, you need a block, how else would perl know where the variable is local.
The block is not ugly imo. I often use blocks in perl just to declare local variables. There is a way to avoid such blocks, but that involves changing programming style: you have to write short (50 lines most) subroutines that do one thing and do it well, and you can declare local variables at the top of each subroutine, with one my() statement perl sub (and preferable at most 7 variables). This is a good programming style in C imo (see Documentation/CodingStyle in the linux source), but doesn't always worth in Perl.
This is a bit OT, but note that I write the curlies of a block inline if the block contains only one line of code.
In reply to Re: A cleaner way of scoping variables
by ambrus
in thread A cleaner way of scoping variables
by bradcathey
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |