Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: arrays and lists, hmmm

by Athanasius (Archbishop)
on Apr 26, 2016 at 03:29 UTC ( [id://1161510]=note: print w/replies, xml ) Need Help??


in reply to arrays and lists, hmmm

Hello morgon,

I would have expected $y also to be 2, but instead the last element of the list is used instead...

But there is no list. I think what’s confusing here is that parentheses are used in Perl to make lists. But that only works in list context. In scalar context, as here, parentheses are only for grouping,1 which in this case makes no difference:

13:20 >perl -wE "my $y = ('a', 'b'); say $y;" Useless use of a constant ("a") in void context at -e line 1. b 13:20 >perl -wE "my $y = 'a', 'b'; say $y;" Useless use of a constant ("b") in void context at -e line 1. a 13:20 >

From perldata#List-value-constructors:

List values are denoted by separating individual values by commas (and enclosing the list in parentheses where precedence requires it):
        (LIST)
In a context not requiring a list value, the value of what appears to be a list literal is simply the value of the final element, as with the C comma operator.

Update: 1Actually, parentheses are only used for grouping (precedence), regardless of context, as indicated in the perldata quote. My statement that parentheses are used to make lists is a little misleading: they are generally needed, but only because the assignment operator has higher precedence than the comma operator:

14:05 >perl -MData::Dump -wE "my @a = 't'; dd \@a;" ["t"] 14:13 >perl -MData::Dump -wE "my @a = 't', 'u'; dd \@a;" Useless use of a constant ("u") in void context at -e line 1. ["t"] 14:13 >perl -MData::Dump -wE "my @a = ('t', 'u'); dd \@a;" ["t", "u"] 14:13 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: arrays and lists, hmmm
by morgon (Priest) on Apr 27, 2016 at 02:02 UTC
    Very cool.

    I have always thought parentheses would create a list.

    Oh well, a life time is probably not enough to master perl (a quite dubious compliment though...).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1161510]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-03-30 09:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found