Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Split the array elements in ranges

by viktor (Acolyte)
on Apr 16, 2013 at 10:00 UTC ( #1028859=perlquestion: print w/replies, xml ) Need Help??
viktor has asked for the wisdom of the Perl Monks concerning the following question:

Hi, Can anyone tell me that if we have any module in cpan which can split the array elements in blocks of say 10. For example

@array=qw ( 1 2 3 10 11 12 13 20 21);

I want the output like this 1-10 5, 11-20 4, 20-30 1 thanks

Replies are listed 'Best First'.
Re: Split the array elements in ranges
by hdb (Prior) on Apr 16, 2013 at 10:17 UTC

    What you want is some Histogram. Have a look at CPAN. Otherwise, use a hash for counting:

    use strict; use warnings; my @array=qw ( 1 2 3 10 11 12 13 20 21); my $bin = 10; my %hist; map { $hist{ (int(($_-1)/$bin)+1)*$bin }++ } @array; print join ",", map { ($_-9)."-$_ $hist{$_}" } sort keys %hist;
      thanks :)
Re: Split the array elements in ranges
by prashantktyagi (Scribe) on Apr 16, 2013 at 10:13 UTC
Re: Split the array elements in ranges
by jwkrahn (Monsignor) on Apr 16, 2013 at 18:47 UTC

    List::MoreUtils has the natatime() function and it is probably already installed on your computer.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1028859]
Approved by kcott
[prathap keerthipati]: how to update perl in unix
[hippo]: yum update perl
[hippo]: Other package managers are available
LanX wouldn't update system Perl!
[Discipulus]: prathap keerthipati might be it is better to install an alternative Perl instead and do not touch the system one
[LanX]: see perlbrew for alternative Perl installations
[marto]: unless you know exactly what you're doing an often saner option is to simply build another Perl rather than replace the system one

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (16)
As of 2017-03-23 10:36 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (285 votes). Check out past polls.