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

Re: [FWP] Formatting integer sets with ranges



> 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.  I remembered that there was a module to do this (it is

I was about to reply with a simple regex:

  s/(\d+)-(\d+)/join ",", $1..$2/eg;

when I realized you want the conversion in the OTHER direction.  "Well!"
I thought to myself.  Could a regex be used to convert it thus?

I couldn't find one that would work for my version of Perl.  :(

I came up with this, nothing like what you wished for, and prolly slower,
too:

  @parts = split /,/, $range;
  for ($i = 0; $_ = $parts[$i]; $i++) {
    $b = $_, next if !defined $b or !defined $t and $_ - $b > 1;
    $t = $_, next if !defined $t or $_ - $t == 1;
    $range =~ s/$b.*?$t/$b-$t/;
    ($b,$t) = ($_);
  }
  $range =~ s/$b.*?$t/$b-$t/ if $b and $t and $i == @parts;

Ick, eh? :)

-- 

  MIDN 4/C PINYAN, USNR, NROTCURPI     http://www.pobox.com/~japhy/
  jeff pinyan: japhy@pobox.com     perl stuff: japhy+perl@pobox.com
  "The Art of Perl"               http://www.pobox.com/~japhy/book/      
  CPAN ID: PINYAN  http://www.perl.com/CPAN/authors/id/P/PI/PINYAN/
  PerlMonth - An Online Perl Magazine     http://www.perlmonth.com/


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