Making a subroutine, if you want it to use values
rather than variables, the way to do it
is string eval. ("evaluation strategy",
indeed.)
use warnings;
use strict;
my @d;
for (my $i = 0; $i<3; $i++) {
push @d, eval qq/sub { print "$i\n" }/;
}
&{$d[0]}();
&{$d[1]}();
&{$d[2]}();
However, you will note that since the value of $i
through this loop was 0, 1, and 2, that's what you get
in output as well ... not 1, 2, and 3 :-)
Alternatively, you can choose to use variables, but then
you need three variables. The above code makes only one.
The below code uses three variables (all with the same
name), and also prints 0, 1, and 2:
use warnings;
use strict;
my @d;
for (my $i = 0; $i<3; $i++) {
my $closure_var = $i;
push @d, sub { print "$closure_var\n" };
}
&{$d[0]}();
&{$d[1]}();
&{$d[2]}();
The Sidhekin
print "Just another Perl ${\(trickster and hacker)},"
-
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.