[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Formatting integer sets with ranges



In article <f9kd4gzkg+BG092yn@efn.org>, I wrote:
>I had to write a throwaway script to (among other things) print a
>sorted array of integers like 1,2,3,5,6,8,10 as a list of ranges like
>1-3,5-6,8,10.
[snip]

>but it seems like there should be a somewhat simpler way to do this
>(along the lines of "print map ...").  Any takers?

I came up with this, but I hate it:

my ($prev, $beg);
print map(!$prev ? ($beg = $prev = $_) :
          $_ == $prev+1 ? do {++$prev; ()} :
          do { my $xprev = $prev;
          (($beg != $xprev ? ('-', $xprev) : ()), ',',$beg = $prev = $_)},
          @issues),
      $beg != $prev ? ('-', $prev) : ();
print "\n";

The do { my $xprev stuff I needed to work around what seems like a perl bug.

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe