my %hash = ('test1' => 'test1', 'test10' => 'test10', 'test100' => 'test100', 'foo' => 'testfoo'); foreach my $bid (sort {substr ($a,4) <=> substr ($b,4)} grep {/^test(\d+)$/} keys %hash) { print "$bid\n"; }