Hi Monks,

Good Day.

Today in one of my program, I got wrong output and when I went through the code, it is because of scoping problem in if statements.

Then I went through the Perl Documentation and it says the following:

Note that the braces are required in Perl, even if you've only got one line in the block. However, there is a clever way of making your one-line conditional blocks more English like:

# the traditional way if ($zippy) { print "Yow!"; } # the Perlish post-condition way print "Yow!" if $zippy;
When I tested with example, I am getting the following outputs

my $x = 10; #case 1: if (1){ my $x = 5; } print $x; #prints 10 #case 2: my $x = 5 if (1); print $x; #prints 5

I know the variable declared with my inside a block will have scoping till the block ends, which works fine in case 1, but not in case 2. If so, then how the document says both are equal and the difference is Perlish way.

Is both statements are equal or different? Could someone enlighten me?

Thanks in advance

Prasad


In reply to How scoping works in If statements? by prasadbabu

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.