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


In reply to Re: A cleaner way of scoping variables by Crackers2
in thread A cleaner way of scoping variables by bradcathey

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.