Here is another way to do it. As we have the values in a hash we can easily see if we also have $value+1. It does not come close to the elegance of the regex linked above. sub bar is a drop in replacement for sub foo.
sub bar { my %hash = @_; foreach (keys %hash) { if (exists $hash{$_+1}) { $hash{$_}="." }else{ $hash{$_}="" } } my @array = ( sort {$a <=> $b} (keys %hash) ); my $string = shift @array; $string.=$hash{$string}; foreach (@array) { $string .= ", $_$hash{$_}"; } $string=~s/(, (\d+)\.)(, (\d+)\.)*/, $2../g; $string=~s/\.\., /../g; print "\n($string)\n"; } # updated ! this is a nicer way to print the output sub bar { my %hash = @_; foreach (keys %hash) { if (exists $hash{$_+1}) { $hash{$_}="." }else{ $hash{$_}="" } } my @array = ( sort {$a <=> $b} (keys %hash) ); my $last=pop @array; my $lastdot=0; print "\n("; foreach (@array) { if ($hash{$_}) { next if $lastdot; print "$_.."; $lastdot++; } else { print "$_, "; $lastdot=0; } } print "$last)\n"; }
Cheers,
R.
In reply to Re: Display array as ranges?
by Random_Walk
in thread Display array as ranges?
by xipho
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |