On Tue, Sep 16, 2014 at 02:43:28PM -0500, Andy Bach wrote:
> On Tue, Sep 16, 2014 at 1:45 PM, Paul Johnson <p...@pjcj.net> 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 ...???

Aha, turning it up a notch ;-)

In this case, ('first', 'second', 'third') is actually a list.  Why?
Because the [1] indexes into it.  The [1] forces it into list context.
You can't index into something that is in scalar context.

> $ perldoc -q 'difference between a list and an array'

> 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 ..

Yes, I think the search is only on the title of the section, not its
contents.  Which can mean that you need to find what you are looking for
in order to know how to find it.

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

-- 
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