In Perl, the array index -1
means the last element:
@F=(1,2,3);
print $F[-1]; # result: 3
You can also use the $#
notation instead, here $#F
:
@F=(1,2,3);
print $F[$#F]; # result: 3
So why don't -1
and $#F
give the same result when I want to specify the last element in a range:
print @F[1..$#F]; # 23
print @F[1..-1]; # <empty>
The array @F[1..-1]
should really contain all elements from element 1
to the last one, no?
Your problem is the @a[b..c]
syntax involves two distinct operations. First b..c
is evaluated, returning a list, and then @a[]
is evaluated with that list. The range operator ..
doesn't know it's being used for array subscripts, so as far as it's concerned there's nothing between 1 and -1. It returns the empty list, so the array returns an empty slice.