JadeNB has asked for the wisdom of the Perl Monks concerning the following question:
Now, if I write my $return = prepend_to(my $a)->(my $b), then $return->[1] = 3 changes $b, but $return->[0] = 3 does not change $a. This confuses me, since it seems that $a is only ever getting passed around as part of a subroutine call or a for loop, neither of which should be making a copy.sub prepend { for ( @_ ) { return sub { return sub { \@_ }->($_, @_); }; } }
The strange thing is, if I change the for invocation to for my $a ( @_ ) (and the $_ later to $a), then everything works just as I'd expect. My question is: Why? Does sub compile in the value of $_, but look in its pad for a named variable like $a; or is it something more subtle?
P.S. The ‘too lazy’ in the title refers to the fact that I know I could just do this my capturing a reference to $_[0] early on in prepend and then de-referencing it in the subroutine, but I'd rather avoid doing all that hard work by nesting subs 7 levels deep. :-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Too lazy to be lazy
by ikegami (Patriarch) on Jul 29, 2009 at 22:25 UTC | |
by JadeNB (Chaplain) on Jul 29, 2009 at 23:13 UTC | |
|
Re: Too lazy to be lazy
by Anonymous Monk on Jul 29, 2009 at 20:24 UTC | |
by JadeNB (Chaplain) on Jul 29, 2009 at 20:46 UTC |