First off, you don't need a fancy sort subroutine if all you're using is regular numbers. The famous "spaceship operator" (<=>) will do quite nicely.(see below.)
#!/usr/bin/perl -w use strict; # example input string my $in = '1089,3,4,5,6,7,99,832,1087,831,1088'; # split the scalar my @i = split(/,/,$in); # to sort by number just use $a <=> $b instead # of the default $a cmp $b @i = sort {$a <=> $b} @i; # load a hash to make looking up existing numbers easy my %lookup; foreach my $number(@i) { $lookup{$number} = 1; } # now check the numbers for consecutiveness, and # put the results in @output my @output; my $end_number=0; foreach my $number (@i) { # skip the numbers already included in a range next if $number <= $end_number; # find the end_number in a range $end_number = $number; $end_number++ until !$lookup{$end_number+1}; # and add to @output whether the range has # one or more numbers in it if ($number == $end_number) { push @output, $number; } else { push @output, "$number-$end_number"; } } print "$_\n" for @output;
There's lots more fancy ways of doing this. The code above is optimized for read-ability and learn-ability.

(and, for the record, yes, it looks a little homework-ey, but anyone who posts code has at least given it a shot.)

Gary Blackburn
Trained Killer


In reply to Re: Sorting and ranging problems... by Trimbach
in thread Sorting and ranging problems... by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.