budman has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I needed a routine to take number runs and show them as ranges. Example: 1,2,3,4,7,8,10,11,12,13,20 Would format to: 1-4,7,8,10-13,20 This is the first attempt at it. Any optimization suggestions would be appreciated. :)
#!/usr/bin/perl -w my @Times = (1,2,3,4,7,8,9,12,14,15,19,20,21,22,23); my $index = 0; my @v; while ( $index <= $#Times ) { $t = $Times[$index]; push @v, $t; last if $index == $#Times; $count = 0; foreach $k ( @Times[ $index + 1 .. $#Times] ) { printf "I: %2d T: %2d C: %2d K: %2d\n", $index,$t,$count,$k; if ( $t + $count + 1 == $k ) { $count++; } else { last; } } if ( $count >= 2 ) { $index += $count; push @v, ("-", $Times[ $index ] ); } $index++; } print "Original: ", join(",",@Times), "\n"; $str = join(",",@v); print "Consolidated: $str\n"; my $formatted = $str; $formatted =~ s/,-,/-/g; print "Formatted: $formatted\n"; my $fmttime = $formatted; $fmttime =~ s/(\d+)/sprintf("%d%sm",($1>12?$1-12:($1==0?"12":$1)), ($1<12?"a":"p"))/eg; print "Time Fmt: $fmttime\n";
Here is a sample of the output:
I:  0 T:  1 C:  0 K:  2
I:  0 T:  1 C:  1 K:  3
I:  0 T:  1 C:  2 K:  4
I:  0 T:  1 C:  3 K:  7
I:  4 T:  7 C:  0 K:  8
I:  4 T:  7 C:  1 K:  9
I:  4 T:  7 C:  2 K: 12
I:  7 T: 12 C:  0 K: 14
I:  8 T: 14 C:  0 K: 15
I:  8 T: 14 C:  1 K: 19
I:  9 T: 15 C:  0 K: 19
I: 10 T: 19 C:  0 K: 20
I: 10 T: 19 C:  1 K: 21
I: 10 T: 19 C:  2 K: 22
I: 10 T: 19 C:  3 K: 23
Original:     1,2,3,4,7,8,9,12,14,15,19,20,21,22,23
Consolidated: 1,-,4,7,-,9,12,14,15,19,-,23
Formatted:    1-4,7-9,12,14,15,19-23
Time Fmt:     1am-4am,7am-9am,12pm,2pm,3pm,7pm-11pm
I was wondering is it possible to do the above with a regex as well? Regards, budman

Replies are listed 'Best First'.
Re: Consolidate Sequential Number Runs
by Coruscate (Sexton) on Jan 22, 2004 at 08:21 UTC
      Thanks for the list and helpful *search* words. :)
      I must of tried all different combinations. hehe
      I looked at some of the code, funny how many different ideas and approaches to one problem exist. :)