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

后端 未结 10 957
我在风中等你
我在风中等你 2020-12-15 20:37

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

10条回答
  •  甜味超标
    2020-12-15 21:36

    Another way would be by using grep:

    my @array = qw( zero one two three four five six );
    
    print map { "$_ " } @array[grep { !($_ & 1) } 0 .. $#array];  #even
    Output:zero two four six
    
    print map { "$_ " } @array[grep { ($_ & 1) } 0 .. $#array];  #odd
    Output:one three five 
    

提交回复
热议问题