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);