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

  • Comment on If it looks like a scalar, and quacks like an array, it's still a scalar.
  • Download Code

Replies are listed 'Best First'.
Re: If it looks like a scalar, and quacks like an array, it's still a scalar.
by bart (Canon) on Dec 25, 2003 at 22:28 UTC
    the very FETCH() method believes its being invoked in scalar context, even if we're trying to assign to an array.
    Good. I mean: any other behaviour by Perl, in such cercumstances, would have to be considered a bug. Now, you've verified that there is no such bug.

    p.s. Even if you've convinced yourself that there's no point in such experiments, I think there is: you're exploring the very corners of Perl.

Re: If it looks like a scalar, and quacks like an array, it's still a scalar.
by dragonchild (Archbishop) on Dec 30, 2003 at 19:28 UTC
    If you tie to an array and assign it to another array, FETCH() is called in sequence, but still in scalar context. There is no FETCH_ALL() method, for either arrays or hashes.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.