# 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; }