On Dec 17, Jeff 'japhy' Pinyan said:

>The computer science way is to split the string into a list of numbers,
>and then go through the list one number at a time.  Keep track of the
>first number of the potential "range", as well as the last number
>seen.  If the current number is one more than the last number, then keep
>going.  Once you get a number that is NOT one more than the previous, you
>generate a range.  Here's the code:

I'm sorry.  I forget the ending clean-up.

After you've gone through the list, you need to add what's in the
"buffer" (the values in $first and $last) to @output.  Otherwise, the last
thing in your list never gets accounted for.

>  sub list2range {
>    my $list = shift;
>    my ($first, $last);
>    my @output;
>
>    # remove the first number in the list...
>    # and set $first and $last to it
>    $list =~ s/^(\d+),?// and $first = $last = $1;
>
>    for (split /,/ => $list) {
>      # next number in the range
>      if ($_ == $last + 1) {
>        $last = $_;
>        next;  # get the next number
>      }
>
>      # otherwise, we're done with the current range
>      # don't use "3-3", just use "3"
>      if ($first == $last) {
>        push @output, $first;
>      }
>      else {
>        push @output, "$first-$last";
>      }
>
>      # now $_ is the first number in a new range
>      $first = $last = $_;
>    }       

     # clean-up time
     # take care of the last part of the list
     if ($first == $last) {
       push @output, $first;
     }
     else {
       push @output, "$first-$last";
     }

>    return join "," => @output;
>  }

On a side note, that's why I like the regex solution.  Far less "real
work" involved.

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to