in reply to A cleaner way of scoping variables
But if $bar is still in scope after the if, how is this any different from just declaring it right before the block ?
In your example you use the extra braces to limit the scope of your variable to prevent it from being a global. If your "preferred" code would be allowed, where do you think $bar should go out of scope? i.e. :
if ($foo) { my $bar = "true"; } print $bar; print "again" . $bar; #-- does this still work <cut 500 lines> print "and again" . $bar; #-- what about this?
If all those prints work, your code is essentially the same as when you just declare $bar before the if block. If not, at what point does $bar go out of scope ?
Another point: what happens in your code if the condition is false? Would you want a runtime error (because $bar is not declared in that case) ? Or are you thinking more of declaring $bar in both the if and else branch?
There's one possible case where I could see your suggestion being somewhat useful, namely something like this:
my $bar = "hello"; #-- global sub mysub { if (condition) { my $bar = "goodbye"; } print $bar; }
So to summarize, my main question to you is: when would $bar go out of scope in the code you propose
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: A cleaner way of scoping variables
by ihb (Deacon) on Aug 09, 2004 at 19:07 UTC | |
|
Re^2: A cleaner way of scoping variables
by bradcathey (Prior) on Aug 09, 2004 at 16:38 UTC |