OK. While at this point, it will seem
quite obvious. I'm going to list it, for
completeness. As I would have thought it the first thing to show up. :)
Here cant i declare a variabe without using my keyword.
Error: Global symbol "$i" requires explicit package name at for.pl line 6.
Technically, you can
use strict;
use warnings;
my $number=8;
no strict; # could have also used "no strict vars"
$i=0; #if i remove my keyword it gives error (not now)
for($i=0;$i<20;$i++)
use strict; # back to strict
{
print "present value of the number is:";
print $number++;
print "\n";
}
OR, clobber them all up front:
use strict;
no strict vars;
use warnings;
$number=8; # look MA, no MY!
$i=0; #if i remove my keyword it gives error -- not NOW!
for($i=0;$i<20;$i++) # here either
{
print "present value of the number is:";
print $number++;
print "\n";
}
OK those were pretty much directly from the
strictures documentation (which is why I felt they should have been included here). But why not illustrate another possibility -- global
Variable Scoping in Perl: the basics?
#!/usr/bin/perl -w
our ( $number, $i );
use strict;
$number=8; # NOTE the absence of my
$i=0; # AGAIN no my used here
for($i=0;$i<20;$i++) # OR here
{
print "present value of the number is:";
print $number++;
print "\n";
}
Cool, huh? Well, not really. While the PHP language practically
encourages global variables. In most cases, it should be avoided. If for no other reason;
security reasons.
Ovid has written a nice overview, that outlines global variables
scoping, titled:
'our' is not 'my', that better describes this.
There. Now this feels complete :)
--Chris
¡λɐp ʇɑəɹ⅁ ɐ əʌɐɥ puɐ ʻꜱdləɥ ꜱᴉɥʇ ədoH
-
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.