Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I write @F[1..-1] to get elements 1..last?

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?

like image 676
Frank Avatar asked Nov 28 '22 00:11

Frank


2 Answers

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.

like image 114
ChrisV Avatar answered Dec 18 '22 07:12

ChrisV


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[()].

like image 31
ysth Avatar answered Dec 18 '22 06:12

ysth