When calling keys %hash, you load all keys in memory at once. This can take quite some time if your database is not small. Are you sure your programm hangs dead? How long have you been waiting? Maybe a look at a process watcher such as top could help.
Normally to loop through the keys of a tied database you should use the tied object (not the tied hash, see below) and a cursor using the seq method:
my $X = tie my %hash, 'DB_File', $filename;
my ($key, $value);
for (
my $status = $X->seq($key, $value, R_FIRST);
$status == 0;
$status = $X->seq($key, $value, R_NEXT)
) {
...
}
I advise you to do something like that if you really need sequential access.