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