xipho has asked for the wisdom of the Perl Monks concerning the following question:
sub foo () { my %hash = @_; my @array = ( sort {$a <=> $b} (keys %hash) ); my $j = shift @array; my ($periods, $i); my $string = "($j"; foreach $i (@array) { if ($i == $j + 1) { $periods = 1; } else { if ($periods) { $string .= "..$j, $i"; } else { $string .= ", $i"; } $periods = 0; } $j = $i; } if ($periods) { $string .= "..$j)" } else { $string .= ")"; } return $string; } # a test my @test_nums = (0, 10, 11, 12, 2, 4, 3, 5, 6, 7, 9); my %test; # pass via hash, only because I ultimately need to foreach my $num (@test_nums) { $test{$num} = undef; } #test print &foo(%test);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Display array as ranges?
by BrowserUk (Patriarch) on Jan 17, 2005 at 05:29 UTC | |
by xipho (Scribe) on Jan 17, 2005 at 05:38 UTC | |
|
Re: Display array as ranges?
by Zaxo (Archbishop) on Jan 17, 2005 at 05:25 UTC | |
|
Re: Display array as ranges?
by chromatic (Archbishop) on Jan 17, 2005 at 08:19 UTC | |
|
Re: Display array as ranges?
by Errto (Vicar) on Jan 17, 2005 at 07:36 UTC | |
|
Re: Display array as ranges?
by xipho (Scribe) on Jan 17, 2005 at 05:09 UTC | |
|
Re: Display array as ranges?
by davido (Cardinal) on Jan 17, 2005 at 04:49 UTC | |
|
Re: Display array as ranges?
by Random_Walk (Prior) on Jan 17, 2005 at 12:08 UTC |