I'm guessing functions are called differently (internally) based on the expected context, which would explain why (wantarray ? @r : $r) = func() doesn't work. If so, that means the second call to the wrapped function cannot be eliminated.

The following works if the call to the wrapped function is done at the end of the wrapping function:

#!perl -l my $code = sub { wantarray ? 1 : 0 }; sub wrapper { # ... later return wantarray ? &$code : scalar &$code; } print wrapper; # 1 print scalar wrapper; # 0

The following is a more general case:

#!perl -l my $code = sub { wantarray ? 1 : 0 }; sub wrapper { my @r = wantarray ? &$code : scalar &$code; # ... later # Convert the array to a list to alter the # behaviour when assigning to a scalar. return @r[0..$#r]; } print wrapper; # 1 print scalar wrapper; # 0

So what's that whole @r[0..$#r] junk? Let me explain by example:

@r = &{ sub { return (4, 5, 6); } }; # 4, 5, 6 @r = &{ sub { my @r = (4, 5, 6); return @r; } }; # 4, 5, 6 @r = &{ sub { my @r = (4, 5, 6); return @r[0..$#r]; } }; # 4, 5, 6 $r = &{ sub { return (4, 5, 6); } }; # 6 $r = &{ sub { my @r = (4, 5, 6); return @r; } }; # 3 $r = &{ sub { my @r = (4, 5, 6); return @r[0..$#r]; } }; # 6

Update: Non-code changes to make things more readable.

Update: The following also works in the case where the call to the wrapped function is done at the end of the wrapping function. However, wrapper will not appear in the call stack (as seen by caller, cluck and confess, for example).

#!perl -l my $code = sub { wantarray ? 1 : 0 }; sub wrapper { # ... later goto &$code; } print wrapper; # 1 print scalar wrapper; # 0

In reply to Re: Maintaining context of the caller by ikegami
in thread Maintaining context of the caller by revdiablo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.