There's lots more fancy ways of doing this. The code above is optimized for read-ability and learn-ability.#!/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;
(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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |