Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: Converting a list of numbers to use a range operator

by toolic (Bishop)
on Mar 23, 2013 at 20:43 UTC ( #1025071=note: print w/replies, xml ) Need Help??

in reply to [Solved] Converting a list of numbers to use a range operator

I've had this lying around. Is it any less painful?
use warnings; use strict; print ranges(2,3,4,10,11,12), "\n"; sub ranges { my @vals = @_; my $min = $vals[0]; my $max; my @list; for my $i (0 .. (scalar(@vals)-2)) { if (($vals[$i+1] - $vals[$i]) != 1) { $max = $vals[$i]; push @list, ($min == $max) ? $min : "$min-$max"; $min = $vals[$i+1]; } } $max = $vals[-1]; push @list, ($min == $max) ? $min : "$min-$max"; return join ', ', @list; } __END__ 2-4, 10-12

I wonder if Set::IntSpan can do this.

Replies are listed 'Best First'.
Re^2: Converting a list of numbers to use a range operator
by FloydATC (Deacon) on Mar 23, 2013 at 21:22 UTC
    Yes!! Set::IntSpan, I knew I'd seen something like that but couldn't remember what it was called!

    my @array = (2,3,4,10,11,12); my $set = new Set::IntSpan join(',', @array); my $list = $set->run_list; # $list is now "2-4,10-12"
    Now this... this is not ugly :-)

    -- Time flies when you don't know what you're doing

      I even love the way Parse::Range does it.
      Putting your original $list in the function parse_range prints out beautifully like so:

      use warnings; use strict; use Parse::Range qw(parse_range); my $list = "2-4,10-12"; print join ','=> parse_range($list); # 2,3,4,10,11,12

      If you tell me, I'll forget.
      If you show me, I'll remember.
      if you involve me, I'll understand.
      --- Author unknown to me

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1025071]
[Corion]: Meh... For bringing Perl into the Enterprise, I need to learn more about GSSAPI :-(

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2018-06-21 13:28 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (118 votes). Check out past polls.