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

后端 未结 10 956
我在风中等你
我在风中等你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 21:16

    If you don't mind using an obscure feature of $| you can do this:

    {
        local $|; # don't mess with global $|
        @ar = ( "zero", "one", "two", "three", "four", "five", "six" );
        $| = 0;
        @even = grep --$|, @ar;
        $| = 1;
        @odd = grep --$|, @ar;
        print "even: @even\\n";
        # even: zero two four six
        print "odd: @odd\\n";
        # odd: one three five
    }
    

    or, as a 1 liner:

     { local $|=0; @even = grep --$|, @ar; }
    

    Basically, --$| flip flops between a 0 and 1 value (despite the -- which normally decrements a numeric value), so grep sees a "true" value every other time, thus causing it to return every other item starting with the initial value of $|. Note that you must start with 0 or 1, not some arbitrary index.

提交回复
热议问题