Undeterred by
the proliferation of 'lazy' modules on CPAN, I feel it's time to inflict my own lazy module on the world. Since I'm too lazy to pass around references and de-reference them all over the place, I've had to learn to pay very, very close attention to when I'm using an alias of a value, and when I'm using a copy of it. In particular, I've been twisting and stretching subroutine calls and
fors to avoid copying. Now, however, I'm stuck. I'd like a subroutine that accepts a single scalar value as an argument, and returns a function that returns an arrayref to … err, that's confusing. I want a function
prepend such that
prepend($a)->($b) returns
$return = [ $a, $b ], and that's easy to achieve; but I
also want
$return->[0] = 3 (say) to change
$a, and that seems harder. I eventually came up with
sub prepend {
for ( @_ ) {
return sub {
return sub { \@_ }->($_, @_);
};
}
}
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.
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. :-)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.