On Tue, Jul 01, 2003 at 03:43:31PM +0530, Sudarshan Raghavan wrote: > array vs list, an array in a scalar context evaluates to the > number of elements in it. The same does not apply to a list, > infact I don't think there is a list in scalar context.
Yep. "There is no list... " > my $string = ('one', 'two', 'three'); > #this will result in $string containing 'three' > Reason: What applies here is the comma operator, the result > of the expression is the result of the last sub-expression. Exactly. In scalar context the comma operator returns (the result of) its right-hand side, so a series of commas will return the last item in the series. But in this case, Perl knows in advance that all the elements of the thing-that-looks-like-a-list are constants and that the first two words are going to be discarded. So it just throws them away at compile-time and runs this simplified version: my $string = 'three'; Deparse will show you something cute here: $ perl -MO=Deparse -e '$x = (1,2,3)' -e syntax OK $x = ('???', '???', 3); > @array[0..1] evaluates to a two element list ("apples", "oranges"). > When this is assigned to a scalar, the result will be "oranges" > (the last sub-expression) But no! All together now: "There is no list." I don't think *any* of the builtin operators will return a list in scalar context. (Although subroutines can do so.) Here the "array slice" operator is aware of the scalar context and it (arbitrarily) returns the last element. It could just as easily have returned the first element, or the count, or anything else. I don't mean that it's unpredictable, just that there's no way to explain *why* it returns the last element. That's just what it does. Perhaps the rationale in this particular case is that people are often doing: print "The answer is: ", @a[1] + @b[1]; And they'd run away screaming if they got "2" every time. :-) HTH -- Steve -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]