http://qs1969.pair.com?node_id=803550


in reply to how to push 5th element from one array to another array

Slicy (Pretty efficient):
my @fifth = @arr[ map {$_*5-1} 1..$#arr+4/5 ];
Update: See gmargo's (++) correction below.

     Potentia vobiscum ! (Si hoc legere scis nimium eruditionis habes)

Replies are listed 'Best First'.
Re^2: how to push 5th element from one array to another array
by gmargo (Hermit) on Oct 28, 2009 at 02:29 UTC

    Your code:

    my @fifth = @arr[ map {$_*5-1} 1..$#arr+4/5 ];
    adds a fraction (4/5) to the last array index. So adding appropriate parentheses:
    my @fifth = @arr[ map {$_*5-1} 1..($#arr+4)/5 ];
    seems better but it does not work for all array lengths. (It works if the length modulo 5 is 0 or 1 only.) Changing the 4 to a 1 (aka the array length) does the trick:
    my @fifth = @arr[ map {$_*5-1} 1..($#arr+1)/5 ];