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?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|