Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: Subroutine as an lvalue?

by reptile (Monk)
on May 27, 2000 at 23:52 UTC ( #15160=note: print w/replies, xml ) Need Help??

in reply to Subroutine as an lvalue?

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.


Replies are listed 'Best First'.
RE: Re: Subroutine as an lvalue?
by takshaka (Friar) on May 28, 2000 at 00:16 UTC
    Unfortunately, the above example doesn't really do what the comments claim. $a and $b are never modified.
      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);
      $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.

        Aha. That's it. The explicit return seems to make the sub return the value of the rhs, but the variable is never modified. That's what "experimental" means.

        This works as expected:

        #!/usr/bin/perl -wl use strict; { my $count = 0; sub counter : lvalue { ++$count } } print counter() for 1..5; print counter() = -5; print counter() for 1..5;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://15160]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2018-02-21 03:48 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (274 votes). Check out past polls.