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.
There's nothing special about .. in an array slice; it just generates the requested range and then the slice of that range is looked up.
So @a[-3..-1] => @a[-3,-2,-1], and @a[1..3] => @a[1,2,3], but @a[1..-1] becomes @a[()].
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