Hi lee,

On Sun, 24 Jan 2016 13:11:37 +0100
lee <l...@yagibdah.de> wrote:

> Paul Johnson <p...@pjcj.net> writes:
> 
> > 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 <l...@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.  
> 
> What is the useful use for this operator?
> 

Well, I believe its use was originally inherited from
https://en.wikipedia.org/wiki/C_%28programming_language%29 where one can do
something like:

        x = (y++, y+2);

In Perl 5 though it is preferable to use do { ... } instead:

        $x = do { $y++; $y+2; };

See http://perldoc.perl.org/functions/do.html . GCC and compatible compilers
have a similar feature to Perl 5's do {...} called statement expressions:
https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html .

> > 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'  
> 
> How do you convert an array into a list?
> 

You just put it in list context. For example (untested):

sub f
{
        print (@_);
}

my @input = (3, 44, 505, 6.6);

f(@input);

my @other_list = (5,@input,24);

===

Regards,

        Shlomi Fish

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


Reply via email to