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

In reply to Consolidate Sequential Number Runs by budman

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.