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"; }