This is nothing more than a stroll down "what-if" lane. Earlier today I wondered to myself, what happens if I tie a scalar to a class whos FETCH() method attempts to return a list?

You usually hear the other side of the story: "There is no such thing as a list in scalar context." Well, this is just a different twist on the same concept, and with similar outcome. Not really of any use, but I found it thought-provoking.

For a brief moment I even thought it might be possible. But it appears that the scalar's own type provides some notion of context to the class to which it is tied, preventing a tied scalar from returning anything more than a scalar value.

Here's the example code...

package ReturnList; use strict; use warnings; sub TIESCALAR { my ( $class ) = @_; my $self = {}; $self->{Value} = undef; bless $self, $class; } sub STORE { my ( $self, $value ) = @_; push @{$self->{Value}}, $value; return $value; } sub FETCH { my $self = shift; print "List context\n" if wantarray(); return @{$self->{Value}}; } 1; # ---------- Begin main ---------- package main; use strict; use warnings; my $var; tie $var, "ReturnList"; $var = 10; $var = 20; $var = 40; my @array = $var; print @array, "\n"; __OUTPUT__ 3

'3' is the number of elements in the list. This shows that not only is it impossible for a scalar to be anything more than a scalar (even when tied), the very FETCH() method believes its being invoked in scalar context, even if we're trying to assign to an array.

I guess there really isn't a point to this post. But it seemed interesting to me. Anyone else?


Dave


In reply to If it looks like a scalar, and quacks like an array, it's still a scalar. by davido

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.