[prev in list] [next in list] [prev in thread] [next in thread] 

List:       perl-beginners
Subject:    Re: returning arrays
From:       Paul Johnson <paul () pjcj ! net>
Date:       2014-09-09 23:51:03
Message-ID: 20140909235103.GF18079 () pjcj ! net
[Download RAW message or body]

On Tue, Sep 09, 2014 at 03:12:00PM -0700, Jim Gibson wrote:
> 
> On Sep 9, 2014, at 2:57 PM, Shawn H Corey wrote:
> 
> > On Tue, 09 Sep 2014 23:09:52 +0200
> > lee <lee@yun.yagibdah.de> wrote:
> > 
> > > my $i = 1;
> > > my $f = 2.5;
> > > my $s = 'string';
> > > my $list = (1, 2, 3);
> > 
> > No, the count of items in the list gets stored in $list: $list == 3
> 
> Unless the thing on the right-hand-side of the assignment is a 'list' and not an \
> 'array'. This is the one place I can think of where the distinction between 'list' \
> and 'array' actually makes a difference. 
> Compare this:
> 
> my $n = ( 4, 5, 6 );
> 
> with this:
> 
> my @a = ( 4, 5, 6 );
> my $n = @a;
> 
> (Don't try this with the list ( 1, 2, 3 ), either!)


There's a little bit of confusion here.  When you write
> > > my $list = (1, 2, 3);
there isn't actually a list anywhere in that statement, appearances to
the contrary notwithstanding.

To understand what is happening, notice first that the assignment is to
a scalar (confusingly named $list in this case).  That means that the
assignment is in scalar context and so the expression (1, 2, 3) is
evaluated in scalar context.

In scalar context the parentheses () are used for controlling
precedence.  The values 1, 2 and 3 are just scalar values.  And the
commas are comma operators in scalar context.

In scalar context the comma operator evaluates its left-hand side,
throws it away and returns the right-hand side.

This means that the value of (1, 2, 3) in scalar context is 3, and this
is what gets assigned to $list.

What is not happening at all is the creation of a list of numbers and a
calculation of its length.

See also perldoc -q 'difference between a list and an array'

-- 
Paul Johnson - paul@pjcj.net
http://www.pjcj.net

-- 
To unsubscribe, e-mail: beginners-unsubscribe@perl.org
For additional commands, e-mail: beginners-help@perl.org
http://learn.perl.org/


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic