On Tue, Sep 16, 2014 at 1:45 PM, Paul Johnson <[email protected]> wrote:
> The comma operator evaluates its LHS, throws it away, evaluates its RHS
> and returns that. The comma operator is left associative (see perlop).
>
> So the result of evaluating the RHS (1, 2, 3) is:
>
> (1, 2, 3) -> ((1, 2), 3) -> (2, 3) -> 3
>
> And this is why $one_var gets the value 3 - not because there are three
> elements in a list on the RHS.
>
D'oh! Somewhere I knew something like that, that a list in scalar context
ends up assigning the last element to the scalar - though I'm pretty sure I
didn't know it was due to the comma operator. I should have though, as:
# perl -we 'my $one = (3,2,1); print "$one\n"'
Useless use of a constant in void context at -e line 1.
Useless use of a constant in void context at -e line 1.
1
Those two warnings are the "dropping" of the result of the first to comma
operations. Hmm, so this works [1]:
my $second_elem = ('first', 'second', 'third')[1];
$second_elem eq 'second';
because ...???
> This all becomes easier to understand if you don't use the values 1, 2
and 3 :)
I "knew" that was a bad idea ... just not enough to not use it.
$ perldoc -q 'difference between a list and an array'
...
As a side note, there’s no such thing as a list in *scalar context*. When
you say
$scalar = (2, 5, 7, 9);
you’re using the comma operator in *scalar context*, so it uses the
scalar comma operator. There never was a list there at all! This causes
the last value to be returned: 9.
Well, I would've found that if perldoc would've found this for queries on
"scalar context", "list context", "array context" or, for that matter,
plain old "context" but ..
--
a
[1]
perl -we 'my $s_e = ("x", "y", "z")[1]; print "$s_e\n"'
same as:
perl -we 'my $s_e = qw(x y z)[1]; print "$s_e\n"'
and:
perl -we 'my ($s_e) = qw(x y z)[1]; print "$s_e\n"'
Andy Bach,
[email protected]
608 658-1890 cell
608 261-5738 wk