in reply to Maintaining context of the caller

I don't see a way around having duplicated calls to &$code. You can change the way you call &$code based on what your calling context wants. You can even make the destination dependant on what the calling context wants, but this will require you to test wantarray twice; once to determine the lvalue and once to make the correct rvalue call.

$code = sub { wantarray ? ('foot','ball') : 'soccer' }; sub foo { my ($r, @r); # two possible returns (wantarray ? (@r) : ($r)) = # slight of hand to get the +correct lvalue (wantarray ? (&$code) : &$code); # and make the correct rvalu +e call return $r || @r # return that which is defin +ed } $x = &foo(); @x = &foo(); print $x; print @x;

This gives you the ability to do something after your call to &$code. If you did not need this, you could more susictly say:

$code = sub { wantarray ? ("foot","ball") : "soccer" }; sub foo { wantarray ? (&$code) : &$code } $x = &foo(); @x = &foo(); print $x; print @x;

Ivan Heffner
Sr. Software Engineer, DAS Lead
WhitePages.com, Inc.

Replies are listed 'Best First'.
Re^2: Maintaining context of the caller
by revdiablo (Prior) on Jul 05, 2005 at 19:32 UTC

    Thanks for the ideas. I'll chew on them a while and see how they digest. A quick note about your more succinct way. As I also noted in my reply to ikegami, an even more succinct way would be:

    sub foo { &$code }

    The context would propagate automatically.

    Update: to prove it to myself, I ran the following code:

    $ perl -le ' my $code = sub { print wantarray ? "list" : "scalar" }; sub foo { &$code } () = foo; foo'

    And it printed:

    list scalar

    Which verifies that the context propagates.