i need help...im trying to create a way to take a string of numbers seperated by commas, sort them numerically (ala Sorting by_number, credit to ncw), and in the process, turn any consecutive group of numbers into a range (eg: 3,4,5,6,7 would be 3-7), then rejoin all the numbers and ranges of numbers by commas again...now, i've written a script to do this, but it's not even coming close to working, and i can't figure out why...it might be some small thing i'm overlooking, like a missing dash or bracket, or it might be my whole method of doing it...(TMTOWTDI)
# example input string $in = '1089,3,4,5,6,7,99,832,1087,831,1088'; @i = split(/,/,$in); # resort the array numerically @read = sort by_number @i; $list = ''; foreach $i (0..$#read) { if(($read[$i]+1) == $read[$i+1]) { $list .= $read[$i].'-'.$read[$i+1].','; } else { $list .= $read[$i].','; } } $list =~ s/(\d+)\,\1\-/\1\,/g; # output the finished product print $list; # again, credit to ncw for the sort method sub by_number { my @a = split /(\d+)/, $a; my @b = split /(\d+)/, $b; while (@a && @b) { my ($aa, $bb) = (shift(@a), shift(@b)); my $res = ($aa =~ /^\d/ && $bb =~ /^\d/) ? $aa <=> $bb : $aa cmp $bb ; return $res if $res; } return @a <=> @b; }

In reply to 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.