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

后端 未结 10 933
我在风中等你
我在风中等你 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:20

    I'll do this in a two-step process: first generate the desired indices, and then use a slice operation to extract them:

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

    Step-by-step, thats:

    • generate a list of integers from 0 to the last element of the array divided by two
    • multiply each integer by two: now we have even numbers from zero to the index of the last element
    • extract those elements from the original array

提交回复
热议问题