If you are using multiple files in your script and you assume that "use strict" from the main script will automatically affect all the other scripts, you will run afoul of this scoping issue. The scripts below will exhibit different behavior with respect to globals when strict and my are used than when strict and my are not used. If we really want to use $z in our main scope as a global, we should either pass a reference to it in our sub call (and modify it in place), or set its value based on the return value of our sub call. Or we could not use strict, but we should use strict and figure out a better way to handle our data than indiscriminate use of globals.
#!/usr/bin/perl -w
#this is scope1.pl
use strict; #comment out
require 'scope2.pl';
my $z = 0; #comment out, we could also leave this
# undef, but that generates a bunch of warnings
for my $x (1..5)
{
my $y = multiply( $x );
print "$x * 3 : $y : $z\n";
}
_______________________________________
#this is scope2.pl
sub multiply
{
$this = shift;
$z = $this * 3;
}
1;
-
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.
|