use DB_File::Lock; tie(%db_hash, 'DB_File::Lock', "/path/to/my/database", O_RDWR, 0600, $DB_HASH, 'write') or die; 1 while $db_hash{my $num = get_random_number()}; $db_hash{$num}++; ... do something with $num ... untie(%db_hash);