mkHun mkHun - 3 months ago 12
Perl Question

Handle range operator with positive and negative range?

I want to store the second index to fifth element from last index from splitting using range operator.

my $s = "a-b-c-d-e-f-g-f-e-c-a-v-a-t-a-v";
my @ar = (split "-",$s)[2..-5];
print @ar;


Expected output is
c-d-e-f-g-f-e-c-a-v


As like below I want to store

a-b-c-d-e-f-g-f-e-c-a-v-a-t-a-v
| |
2 |
-5
__________________
How to store these element

Answer

The easiest way is to put it in an array and then slice it:

my $s = 'a-b-c-d-e-f-g-f-e-c-a-v-a-t-a-v'; 
my @arr1 = split /-/, $s;
my @arr2 = @arr1[2..@arr1-5];

or

my @arr = do { my @arr = split /-/, $s; @arr[2..@arr-5] };

To do it all at once without an extra variable, you would need to pick an arbitrary size bigger than the array would be and do two slices:

my @arr = grep defined, (grep defined, (split /-/, $s)[2..999])[-999..-5];

(which is much less efficient than just using a separate array).