SPUG: Returning array/list? (Was: "while question")

David Vergin dvergin at igc.org
Tue Sep 16 16:52:24 CDT 2003


Hi Yitzchak (et omnes),

First, let me to offer a more painstakingly transparent example that
illustrates the behavior you are pointing to:

------------------------------------------------
#!/usr/bin/perl -w
use strict;

sub with_array { my @ary = qw/a b c d e/; @ary }
sub with_list  { qw/a b c d e/ }

my $x;

$x = with_array();
print $x, "\n";            # 5
($x) = with_array();
print $x, "\n";            # a

$x = with_list();
print $x, "\n";            # e
($x) = with_list();
print $x, "\n";            # a
-------------------------------------------------

Then let us just note for the record that there is an alternate
explanation of what is happening in these examples. 

There are Perl adepts that argue strongly that what is happening in all
these cases is that the context of the subroutine call is propagating
into the subroutine to the point where a value is returned. Consistent
with that, they would argue that with_array() in a scalar context
returns 5 rather than the @ary array, and that with_list() in a scalar
context returns 'e' rather than the list ('a', 'b', 'c', 'd', 'e').

I'm not trying to advance the ultimate proof of this (I'm not qualified
to do so) -- but just to note for the record that there are different
interpretations by some pretty knowledgable people of the behavior you
originally aluded to in writing of a sub returning an array vs.
returning a list. 

Here are a couple of discussions that touch on this (lively-debated)
question:
http://www.perlmonks.org/index.pl?node_id=72247
http://www.perlmonks.org/index.pl?node_id=26319
http://www.perlmonks.org/index.pl?node_id=33670

Regards,
David V.

On Tue, 2003-09-16 at 22:33, Yitzchak Scott-Thoennes wrote:
> On Tue, Sep 16, 2003 at 03:05:52PM +0000, David Vergin <dvergin at igc.org> wrote:
> > On Tue, 2003-09-16 at 19:26, Yitzchak Scott-Thoennes wrote:
> > > If method() is always returning an explicit list...
> > > ...
> > > If method() is returning an array...
> > 
> > I would be interested to see two simple, contrasting examples of the two
> > behaviors you describe.
> 
> Does this help?
> 
> $ perl -wlne'eval;print$@if$@'
> print "  first: $INC[0]\n  last: $INC[-1]"
>   first: /usr/lib/perl5/5.8.0/cygwin-multi-64int
>   last: .
> sub foo { @INC }
> $x = foo; print $x
> 6
> ($x) = foo; print $x
> /usr/lib/perl5/5.8.0/cygwin-multi-64int
> # now try it with a slice (an array or hash or list converted to a list)
> sub bar { @INC[0..$#INC] }
> $x = bar; print $x
> .
> ($x) = bar; print $x
> /usr/lib/perl5/5.8.0/cygwin-multi-64int
> exit




More information about the spug-list mailing list