Dr. Mu has asked for the wisdom of the Perl Monks concerning the following question:
Otherwise, the object reference of the linked-to object is simply stored as a scalar.$self->{link}->{$linkname} = [@objectrefs]
When the link function is called in list context, I want it to return a list of the linked-to objects, regardless of whether there is just one or many. When it's called in scalar context, I want it to return either a single object if there's only one, or the array reference if there's more than one. Here's what I wrote:
All fine and good. But here's where I get into trouble. There are times when I just want to find out the size of the named link. My first inclination was to use something like scalar $obj->link('next'), for example. Obviously, if the subroutine is returning an argument to scalar, I'm wanting it to return a list so I can measure its size. Right?sub link { my $self = shift; my $linkname = shift; my $link = $self->{link}->{$linkname}; return wantarray ? (ref $link ? @$link : ($link)) : $link }
Well, no, apparently. Rather than acting like a real function, scalar is forcing the context before the subroutine call, as wantarray returns false. So my question is, how can I call link in list context and force the result into scalar context -- without being too ugly about it? (And, yes, I know link is a keyword. I should probably change the sub name to "linkto" or somesuch.)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Confused Contexts and wantarray
by Zaxo (Archbishop) on Jan 18, 2005 at 01:40 UTC | |
by Smylers (Pilgrim) on Jan 18, 2005 at 09:45 UTC | |
|
Re: Confused Contexts and wantarray
by Errto (Vicar) on Jan 18, 2005 at 01:44 UTC | |
|
Re: Confused Contexts and wantarray
by Tanktalus (Canon) on Jan 18, 2005 at 01:26 UTC | |
by MichaelORourke (Initiate) on Jun 15, 2007 at 20:20 UTC | |
by redlemon (Hermit) on Jan 19, 2005 at 00:58 UTC | |
|
Re: Confused Contexts and wantarray
by Dr. Mu (Hermit) on Jan 18, 2005 at 05:28 UTC | |
by ysth (Canon) on Jan 18, 2005 at 07:34 UTC | |
by duff (Parson) on Jan 18, 2005 at 06:00 UTC |