Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: how to push 5th element from one array to another array

by NetWallah (Canon)
on Oct 28, 2009 at 00:31 UTC ( #803550=note: print w/replies, xml ) Need Help??


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 ];

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://803550]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2022-12-01 00:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?