perl

Is there a compact Perl operation to slice alternate elements from an array?


If I have an array myarray in Python, I can use the slice notation

myarray[0::2]

to select only the even-indexed elements. For example:

>>> ar = [ "zero", "one", "two", "three", "four", "five", "six" ]
>>> ar [ 0 : : 2 ]
['zero', 'two', 'four', 'six']

Is there a similar facility in Perl?


Solution

  • There's array slices:

    my @slice = @array[1,42,23,0];
    

    There's a way to to generate lists between $x and $y:

    my @list = $x .. $y
    

    There's a way to build new lists from lists:

    my @new = map { $_ * 2 } @list;
    

    And there's a way to get the length of an array:

    my $len = $#array;
    

    Put together:

    my @even_indexed_elements = @array[map { $_ * 2 } 0 .. int($#array / 2)];
    

    Granted, not quite as nice as the python equivalent, but it does the same job, and you can of course put that in a subroutine if you're using it a lot and want to save yourself from some writing.

    Also there's quite possibly something that'd allow writing this in a more natural way in List::AllUtils.