tags:

views:

83

answers:

3

I'm running the following code and I'm attempting to print the first element in the @rainbow array through the fifth-from-last element in the @rainbow array. This code works for any positive indices within the bounds of the array, but not for negative ones:

@rainbow = ("a".."z");
@slice = @rainbow[1..-5];
print "@slice\n";
+10  A: 

The .. operator forms a range from the left to right value - if the right is greater than or equal to the left. Also, in Perl, array indexing starts at zero.

How about this?

@slice = @rainbow[0..$#rainbow-5];

$#arraygives you the index of the last element in the array.

martin clayton
+6  A: 

You want

my @slice = @rainbow[0 .. $#rainbow - 5];

Be careful, 1 is the second element, not the first.

Chas. Owens
+2  A: 

From the first two sentences for the range operator, documented in perlop:

Binary ".." is the range operator, which is really two different operators depending on the context. In list context, it returns a list of values counting (up by ones) from the left value to the right value. If the left value is greater than the right value then it returns the empty list.

When the code doesn't work, decompose it to see what's happening. For instance, you would try the range operator to see what it produced:

 my @indices = 1 .. -5;
 print "Indices are [@indices]\n";

When you got an empty list list and realized that there is something going on that you don't understand, check the docs for whatever you are trying to do to check it's doing what you think it should be doing. :)

brian d foy