On 02/27/2015 11:24 PM, Martin G. McCormick wrote:
Brock Wilcox writes:
I'm afraid a bit more context is needed to identify the problem. Could you
post your entire bit of code into a gist or pastebin or something for us
to
see?
I'll do better than that. This is a script which is
stripped of everything but the problem code. It is 20 lines long
and here it is.
#!/usr/bin/perl -w
use strict;
#Declare main variables.
#main locals
my @tasks;
my $task;
my $report_static;
$report_static = sub {
print "$task\n";
};
that $task is bound to the outer $task
#MAIN_CODE START
$tasks[0] = "red";
$tasks[1] = "blue";
$tasks[2] = "green";
that can be done with:
my @tasks = qw( red blue green ) ;
foreach $task (@tasks) {
that $task is localized to the loop (with local()).
see this in perlsyn:
The "foreach" loop iterates over a normal list value and sets the
variable VAR to be each element of the list in turn. If the variable
is preceded with the keyword "my", then it is lexically scoped, and is
therefore visible only within the loop. Otherwise, the variable is
implicitly local to the loop and regains its former value upon exiting
the loop. If the variable was previously declared with "my", it uses
that variable instead of the global one, but it's still localized to
the loop. This implicit localization occurs only in a "foreach" loop.
what are you trying to do here? closures are very useful but rarely do
beginners need them and there is no need in that example and likely in
your real problem as well. i smell an XY problem and you are likely to
just need better data structures or passing data by reference. closures
are not commonly used in basic code - they have a purpose but a rule i
say is you can use an advanced feature until you know when you are not
supposed to use it.
thanx,
uri
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/