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; }

i.e. where the sub-local variable would obscure an already-existing global. But this is both ugly and bad design.

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

    If all those prints work, your code is essentially the same as when you just declare $bar before the if block.

    Almost, but not quite. You could have code between the start of the if block and the $bar declaration that wasn't allowed to use $bar if using what the OP was asking for. I'm not saying that this is something I want, because as you say, it would be like a global except you can't use it above the statement. But I think that's the detail that the OP was thinking about.

    ihb

    Read argumentation in its context!

Re^2: A cleaner way of scoping variables
by bradcathey (Prior) on Aug 09, 2004 at 16:38 UTC
    Thanks much Crackers2, excellent points all well taken. Your last question is a zinger and I really can't answer that. I do like your suggestion of keeping in within a sub, but other than that, I think my original OP was a bit presumptuous in trying to suggest something basically impossible in Perl (or any other language for that matter).

    —Brad
    "Don't ever take a fence down until you know the reason it was put up. " G. K. Chesterton