thenickname
thenickname

Reputation: 6975

How can I print the first to the fifth from last array elements in Perl?

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

Upvotes: 26

Views: 52382

Answers (3)

brian d foy
brian d foy

Reputation: 132920

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 and realized that there is something going on that you don't understand, check the documentation for whatever you are trying to do to check it's doing what you think it should be doing. :)

Upvotes: 6

Chas. Owens
Chas. Owens

Reputation: 64939

You want

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

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

Upvotes: 43

martin clayton
martin clayton

Reputation: 78215

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.

Upvotes: 18

Related Questions