Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: how to seperate array after a certain number of elements?

by artist (Parson)
on Sep 19, 2007 at 15:51 UTC ( [id://639914]=note: print w/replies, xml ) Need Help??


in reply to how to seperate array after a certain number of elements?

Here is the iterator approach. ( N at a time)
use List::MoreUtils qw(natatime); my @myArray = (1..100); my @myMainArray = (); my $chunkSize = 5; my $iterator = natatime $chunkSize, @myArray; while(my @values = $iterator->()){ push @myMainArray, [@values]; } foreach (@myMainArray){ my @smallArray = @{$_}; print "@smallArray\n"; }
Here is a 'hacked' approach using 'part'.
use List::MoreUtils qw(part); @array = (1..100); $i = -0.1; @parts = part { $i += 0.2 } @array;
--Artist

Replies are listed 'Best First'.
Re^2: how to seperate array after a certain number of elements?
by ikegami (Patriarch) on Sep 20, 2007 at 19:53 UTC

    It's dangerous to repeatedly add decimal numbers since many of them are periodic in binary and therefore cannot be stored precisely. This includes 0.2.

    >perl -le"printf '%.17f', .2 0.20000000000000001

    The following is a safer, simpler and easier to read (since "5" actually appears) version of your second snippet:

    use List::MoreUtils qw(part); my @array = (1..100); my $i; my @parts = part { ($i++)/5 } @array;
      Thanks, I never knew the reason behind it. Very useful tip.
      --Artist

Log In?
Username:
Password:

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

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

    No recent polls found