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";
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.
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.
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.
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.
You want
my @slice = @rainbow[0 .. $#rainbow - 5];
Be careful, 1 is the second element, not the first.
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];
$#array
gives you the index of the last element in the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With