mkHun mkHun - 11 months ago 70
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

As like below I want to store

| |
2 |
How to store these element

Answer Source

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];


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).