That is, as far as I know, a new feature in perl 5.6.0. So first, if you don't have it, you'd better get it. How does it work? Well, this page is all I could find on it (the what's new page).
The example it gives there is this:
my $a = 10;
my $b = 20;
sub mysub : lvalue {
if ($_[0] > 0) { return $a } else { return $b }
}
mysub(2) = 15; # Set $a to 15
mysub(-1) = 9; # Set $b to 9
Not too tough.
Update:I just noticed it also says "This is still an experimental feature, and may go away in the future; it's also not possible to return array or hash variables yet." so keep that in mind.
72656B636148206C72655020726568746F6E41207473754A | [reply] [d/l] |
Unfortunately, the above example doesn't really do what
the comments claim. $a and $b are never modified.
| [reply] |
strange. the following code, which seems equivalent to me,
does work as expected:
my ($a, $b) = (10, 20);
sub mysub : lvalue { $_[0] > 0 ? $a : $b }
mysub(2) = 15;
mysub(-1) = 9;
printf "\$a: %d, \$b: %d, mysub(2): %d, mysub(-1): %d\n",
$a, $b, mysub(2), mysub(-1);
Outputs:
$a: 15, $b: 9, mysub(2): 15, mysub(-1): 9
the only difference that i could see mattering is the
lack of 'return' statements in my version. | [reply] [d/l] |
here's the only copy of the 5.6 perlsub
man page i could find online at
ActiveState.
see the Lvalue subroutines section.
another cool thing along these lines is using builtins
like substr as lvalues. here's an example
(i think it should work with 5.005_03 or higher, possibly
earlier versions):
$foo = "_123_";
substr($foo, 1, 3) = "bar";
print "$foo\n";
_bar_ | [reply] [d/l] |