... strange, in your case I would expect to see a warning like "variables won't stay shared"...
These kind of problems are easily avoided by either using lexical subs:
use strict;
use warnings;
foreach (0, 1) {
my $i = $_;
my $print = sub {
print $i;
};
$print->(); # 0,1
}
or just not expecting to be able to easily redefine package subs at runtime, they are defined only once at compile time:
use strict;
use warnings;
my $i;
sub my_print {
print $i;
};
foreach (0, 1) {
$i = $_;
my_print(); # 0,1
}
Anyway, while there are good use-cases for closures, I'd expect a beginner to go easy and pass arguments normally :
use strict;
use warnings;
sub my_print {
my ($i)=@_;
print $i;
};
foreach (0, 1) {
my_print($_); # 0,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.