I'm trying to write a universal accessor function called link. Its purpose is to access one of an object's many links to another object or collection of objects. When a link refers to a collection of objects, that collection is stored as an array reference, viz:
$self->{link}->{$linkname} = [@objectrefs]
Otherwise, the object reference of the linked-to object is simply stored as a scalar.

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:

sub link { my $self = shift; my $linkname = shift; my $link = $self->{link}->{$linkname}; return wantarray ? (ref $link ? @$link : ($link)) : $link }
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?

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.)


In reply to Confused Contexts and wantarray by Dr. Mu

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.