Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Get ranges from a list of numbers (like 1,2,3 => 1-3)

by Doctrin (Beadle)
on Apr 09, 2013 at 16:26 UTC ( #1027777=perlquestion: print w/replies, xml ) Need Help??
Doctrin has asked for the wisdom of the Perl Monks concerning the following question:

Hello dear Monks. Say, I have a sorted list like this: 1,2,3,4,9,16,22,23,24,30,35 I want to transform it to: 1-4,9,16,22-24,30,35 So that ranges of numbers are spelled as ranges, not as lists. I know how to solve the inverse problem:
use Set::IntSpan; my $span = Set::IntSpan->new('1-4,9,16,22-24,30,35'); print join "," => $span->elements();
would give me 1,2,3,4,9,16,22,23,24,30,35 . Is there a way to make ranges from a list? Maybe, modules similar to Set::IntSpan, or some algorithm?.. Thanks in advance.

Replies are listed 'Best First'.
Re: Get ranges from a list of numbers (like 1,2,3 => 1-3)
by aitap (Deacon) on Apr 09, 2013 at 16:46 UTC
      Thank you! That is exactly what I need!
Re: Get ranges from a list of numbers (like 1,2,3 => 1-3)
by SuicideJunkie (Vicar) on Apr 09, 2013 at 16:52 UTC

    Quoth the CPAN:

    print $set->as_string(), "\n"; # prints 1,3,5,7,9,100-1000000

    It sounds like Set:IntSpan already does what you want. Just keep reading down the page a little further to Getting Set Contents

Re: Get ranges from a list of numbers (like 1,2,3 => 1-3)
by LanX (Chancellor) on Apr 09, 2013 at 16:45 UTC
    Same question again in such short interval?

    Smells like homework spirit.

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      Haha, no, that is coincidence... It looks like I should use perlmonks' local search engine... I just googled "perl module to make a range from a list site:perlmonks.org" and did not find that question :( Maybe, searchphrase was not so good. Anyways, thank you very much!
Re: Get ranges from a list of numbers (like 1,2,3 => 1-3)
by daxim (Chaplain) on Apr 09, 2013 at 16:47 UTC
    Call the method run_list, or use the object in string context.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1027777]
Approved by davido
help
Chatterbox?
Ratazong takes a cookie from the platter on the sideboard.
Ratazong adds shortbread cookies to the platter on the sideboard.
[Lady_Aleena]: Hi Ratazong.
[Ratazong]: Hi Lady Aleena
Ratazong just learned about free cookies ;-)
shmem rolls a barrel of beer into the refectorium at the request of jedikaiti

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (9)
As of 2017-04-26 09:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (471 votes). Check out past polls.