views:

80

answers:

2

with

@a=(6,3,5,7);

@b=(@a[0..3])[2..3];

print @b;

#print 57

but for

@b=@a[0..3][2..3];

I get a syntax error. Could someone explain why?

+3  A: 
@a=(6,3,5,7);

This creates an array with 4 elements.

(@a[0..3])

This returns a list with the same four elements as @a.

(@a[0..3])[2..3];

This selects the last two elements from the 4-element list inside the parenthesis.

print( join( ",", @b ) );

This prints 5,7, the last two elements in @a.

For fun try the following:

@a=(6,3,5,7);
@b=(@a[0..3]);
print( "\@b=" . join(",",@b) . "\n" );
@c=@b[2..3];
print( "\@c=" . join(",",@c) . "\n" );

Note that I used the Perl debugger to understand your program. You could do this, too, if you're not sure what Perl is actually doing from line-to-line.

PP
+8  A: 

The $a[1][2] for is used for 2 dimensional tables, actually it is short for $a[1]->[2]

so for that the first indexing needs to return a reference not a slice of an array.

The syntax error comes from the fact that Perl does not know how to dereference an array.

Peter Tillemans
I guess it means the slice of an array is not list. If it were the second example would compile.
Aftershock
No, it means a slice is not a pointer to another array. In the first example you first evaluate a slice with the parentheses which results in a list, then you take a slice of that. In the second example perl tries to find the array pointed to by the first indexing, it finds an array and not a pointer/reference and fails.
Peter Tillemans