Question

I know @array[0,2,6] is an array with multiple values.

And I was under the belief that $scalar=3 is a single variable with a single scalar value.

However, what is $array[3, 4]? Is it a scalar variable with two values?

Was it helpful?

Solution

@array[0,2,6] (or more generically @array[ EXPR ]) is an array slice. (See perldata) The index expression is evaluated in list context, the returned list is taken to be a list of indexes, and the elements identified by those indexes are returned by the slice.

$array[ EXPR ] is an array element. The index expression is evaluated in scalar context, the returned value is taken to be an index, and the element identified by that index is returned.

The code 3,4 evaluates to 4 in scalar context — See the comma operator in perlop — so $array[3,4] is the same as $array[4] except for a void context warning.

OTHER TIPS

Try it to see:

perl -E '@ar = (10,11,12,42);say $ar[1,2,3]'
42

1,2,3 is a list. In scalar context, it returns its last member.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top