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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |