revdiablo has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Maintaining context of the caller
by ikegami (Patriarch) on Jul 04, 2005 at 19:02 UTC | |
by revdiablo (Prior) on Jul 04, 2005 at 21:31 UTC | |
by diotalevi (Canon) on Jul 04, 2005 at 22:53 UTC | |
by revdiablo (Prior) on Jul 04, 2005 at 23:29 UTC | |
|
Re: Maintaining context of the caller
by brian_d_foy (Abbot) on Jul 04, 2005 at 19:28 UTC | |
by revdiablo (Prior) on Jul 04, 2005 at 21:34 UTC | |
|
Re: Maintaining context of the caller
by GrandFather (Saint) on Jul 04, 2005 at 20:21 UTC | |
by BUU (Prior) on Jul 04, 2005 at 21:43 UTC | |
by GrandFather (Saint) on Jul 04, 2005 at 21:52 UTC | |
by BUU (Prior) on Jul 04, 2005 at 21:54 UTC | |
by GrandFather (Saint) on Jul 04, 2005 at 22:03 UTC | |
| |
by ysth (Canon) on Jul 04, 2005 at 22:13 UTC | |
| |
by gellyfish (Monsignor) on Jul 04, 2005 at 21:49 UTC | |
| |
|
Re: Maintaining context of the caller
by bsb (Priest) on Jul 05, 2005 at 02:56 UTC | |
by revdiablo (Prior) on Jul 05, 2005 at 15:59 UTC | |
|
Re: Maintaining context of the caller
by Codon (Friar) on Jul 05, 2005 at 19:24 UTC | |
by revdiablo (Prior) on Jul 05, 2005 at 19:32 UTC |