Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
# 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; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Sorting and ranging problems...
by Trimbach (Curate) on Sep 27, 2001 at 03:30 UTC | |
|
(Golf!) Re: Sorting and ranging problems...
by demerphq (Chancellor) on Sep 27, 2001 at 05:45 UTC | |
|
Re: Sorting and ranging problems...
by dragonchild (Archbishop) on Sep 27, 2001 at 03:07 UTC | |
by Anonymous Monk on Sep 27, 2001 at 08:49 UTC |