I want to store the return values from a sub, and return them later, but I want to call the sub in the same context as the original caller. It works great doing it the obvious way:

my (@r, $r); if (wantarray) { @r = &$code } else { $r = &$code } # ... later return wantarray ? @r : $r;

I was wondering if there was perhaps a less obvious way. My main problems with this code are: (1) wantarray is checked twice, and (2) &$code is repeated. (Before anyone asks: yes, I am aware that @_ is being passed implicitly. This is the behavior I want.)

Problem (1) could be trivially "solved" by storing wantarray's return value, but then that variable would have to be checked twice. It's not really the call itself that bothers me, but the fact that the logic is duplicated. I'm not sure if it's possible or even desireable to avoid this, but maybe there's some idiom I am unaware of.

I thought I could solve problem (2) with the following:

wantarray ? @r : $r = &$code;

But that gives me an error, Assignment to both a list and a scalar. (Again, before anyone asks: no, it's not a precedence problem. I even tried adding appropriate parentheses just to be sure.)

Any ideas would be welcome. This isn't a showstopper, and I certainly have code that behaves as desired, but this seems like something that would have a nice little idiom or two to support it.


In reply to 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.