Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"; 
like image 728
thenickname Avatar asked Jan 08 '10 00:01

thenickname


People also ask

How do I get the second last element of an array in Perl?

Perl provides a shorter syntax for accessing the last element of an array: negative indexing. Negative indices track the array from the end, so -1 refers to the last element, -2 the second to last element and so on.

How do I get the last element of an array in Perl?

Perl returns element referred to by a negative index from the end of the array. For example, $days[-1] returns the last element of the array @days . You can access multiple array elements at a time using the same technique as the list slice.

How do I print the first element of an array in Perl?

The index of the first array element is 0. For example: # Multiple elements value assignment, which creates an array with four elements, some numeric and some string. @array = (25, "John", "Mary", -45.34); print "$array[1]\n"; # John # Direct assignment of an element with a specific index.

How do I print an array of data in Perl?

use 5.012_002; use strict; use warnings; my @array = qw/ 1 2 3 4 5 /; { local $" = ', '; print "@array\n"; # Interpolation. } Enjoy! Show activity on this post. Data::Dumper is a standard module and is installed along with Perl.


2 Answers

You want

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

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

like image 91
Chas. Owens Avatar answered Sep 19 '22 18:09

Chas. Owens


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.

like image 22
martin clayton Avatar answered Sep 17 '22 18:09

martin clayton