And just to fool around with the above code, the following example emphasizes the previous point that what matters is the current value of the global $_ when the anonymous sub runs, not its value at its time of creation.
Whereas with the lexical version, what matters is the value of lexical $i at time of creation
my (%withlex, %withglobal);
for (1 .. 10) {
my $ref = sub { return $_ };
$withglobal{$ref} = $ref;
print $ref->(), "\n";
}
print keys %withglobal;
print "\n";
$_ = 'foo';
foreach my $key ( keys %withglobal ) {
print "k: $key\tv: ", &{ $withglobal{$key} }(), "\n";
}
for my $i (1 .. 10) {
my $ref = sub { return $i };
$withlex{$ref} = $ref;
print $ref->(), "\n";
}
print sort { $withlex{$a} <=> $withlex{$b} } keys %withlex;
print "\n";
my $i = 'bar';
foreach my $key ( sort { $withlex{$a} <=> $withlex{$b} } keys %withlex
+ ) {
print "k: $key\tv: ", &{ $withlex{$key} }(), "\n";
}
print "Using lex num of subs is " . (keys %withlex) . "\n";
print "Using global num of subs is " . (keys %withglobal) . "\n";
-
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.
|