Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: take 'n' array elements at a time

by Loops (Curate)
on Nov 18, 2014 at 19:03 UTC ( [id://1107617]=note: print w/replies, xml ) Need Help??


in reply to take 'n' array elements at a time

Doesn't sound too demanding computationally. Create a routine that reads n number of records from a given file, adding all the values and dividing by n. Then run it for every file you're interested in.

Replies are listed 'Best First'.
Re^2: take 'n' array elements at a time
by fionbarr (Friar) on Nov 18, 2014 at 20:07 UTC
    here's what I think I'll use: (the entire file is in @array)
    my @i; while (@array) { last if (scalar @array < 9); push @i, shift @array for 0 .. 8; print join ("\n", @i); print "\n------------------------------------------\n"; @i = (); }
    Thanks

      Hi,

      Well that code is a step in the right direction. Couple things though, you can put the test inside the while loop instead of using "last". You can grab the first 9 items off of the array and delete them from the array in one operation using splice. This lets you avoid using the "@i" array. So:

      my @array = map {$_ * 10} 1 .. 20; # test data while (@array > 8) { print join "\n", splice(@array,0,9); print "\n--------------------\n"; }

      Note that if the array isn't divisible by 9, the last few items will be silently ignored. If you'd rather see them, it's safe to just omit the "> 8".. splice will return whatever remains even though it's not the full 9 items.

        lovely! adding 'splice' to my lexicon thanks

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-04-25 19:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found