in reply to Too lazy to be lazy
When the anon sub instance is created, it is associated with the variables that existed then.
When you use for my $x (or for my $_ in 5.10+), a new $x (or $_) is created for every pass of the loop. When the anon sub instance is created, it is associated with the iterator variable that existed then, a variable that was only used for that loop pass.
When you use for $_, for $_ or for $pkg, the loop simply reuses the existing variable. When the anon sub instance is created, it is associated with the iterator variable that existed then, a package variable whose value will change once the loop pass ends.
(Technically, package vars aren't captured at all. But unless you go mucking with the symbol table, the behaviour is the same as described.)
sub mk_pkg { for our $pkg (@_) { return sub { $pkg } } } sub mk_lex { for my $lex (@_) { return sub { $lex } } } our $pkg = "XXX"; print mk_pkg('abc')->(), "\n"; # XXX print mk_lex('abc')->(), "\n"; # abc
What was confusing me was why, in what seemed to be otherwise identical code, $a was capturing an alias inside the nested subroutine, but $_ was not.
$_ changed value. $a didn't. $a just became anonymous at the end of the loop pass.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Too lazy to be lazy
by JadeNB (Chaplain) on Jul 29, 2009 at 23:13 UTC |