the_0ne has asked for the wisdom of the Perl Monks concerning the following question:
It just looks so un-perlish. It does work and so far I haven't found a combination that breaks it. (The reason I say that is because this is part of a larger script that formats the input from the user like that. So, the numbers will always be in order and comma-delimited before it gets to that chunk of code.) However, it just looks like way too much code to do something so trivial. I won't ask if there is a better way, because Perl wouldn't be Perl if there wasn't. I'd just like to see what other Monks would do with this problem.#! /usr/bin/perl use strict; my $pages = "1,2,3,5,6,7,10,12,13,14,15"; my @pages_arr = split ',', $pages; my (@return_arr, $next_one, $lower_bound, $upper_bound); @return_arr = (); $next_one = ''; $lower_bound = ''; $upper_bound = ''; for (my $x = 0; $x < scalar(@pages_arr); $x++) { $next_one = $pages_arr[$x]; if ($x == 0) { $lower_bound = $upper_bound = $next_one; } elsif ($next_one == ($upper_bound + 1)) { $upper_bound = $next_one; if ($x == (scalar(@pages_arr) - 1)) { push @return_arr, "${lower_bound}-${upper_bound}"; } } elsif ($next_one != ($upper_bound + 1)) { if ($lower_bound == $upper_bound) { push @return_arr, $lower_bound; } else { push @return_arr, "${lower_bound}-${upper_bound}"; } $lower_bound = $upper_bound = $next_one; if ($x == (scalar(@pages_arr) - 1)) { push @return_arr, $next_one; + } } } my $return_var = join ',', @return_arr; print "return_var: ${return_var}\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Combine range of numbers.
by cees (Curate) on Jan 31, 2004 at 04:46 UTC | |
by the_0ne (Pilgrim) on Jan 31, 2004 at 04:56 UTC | |
|
Re: Combine range of numbers.
by japhy (Canon) on Jan 31, 2004 at 04:36 UTC | |
by the_0ne (Pilgrim) on Jan 31, 2004 at 04:54 UTC | |
|
Re: Combine range of numbers.
by jweed (Chaplain) on Jan 31, 2004 at 04:34 UTC | |
by the_0ne (Pilgrim) on Jan 31, 2004 at 04:51 UTC |