In that case, just modify the initial loop to stop after ten hits:
my $how_many = 10;
while (<$fh>) {
if (/^(.+?)\|(.+?)\| (.+?)\s+(\d+)\s+(\d+e[+-]\d+)$/) {
print;
last if --$how_many == 0;
}
}
If that's all you want to do, you don't need the hash. Note that you can still format the output with printf: printf "%-4s %-55s %5s\n", $1, $3, $4;
You could still use the hash, as well, if you need to do further processing on the results. In that case, to preserve the order, either add an index to the hash ref for use with sort, or, simpler, push each key to an array as you find them:
my @hits; # Keys in order
my $how_many = 10;
while (<$fh>) {
if (/^(.+?)\|(.+?)\| (.+?)\s+(\d+)\s+(\d+e[+-]\d+)$/) {
$hash{$2} = { col1 => $1, desc => $3,
score => $4, E => $5, key => $2 };
push @hits, $2;
last if --$how_many == 0;
}
}
# Go through the first ten hits, in order
for (map { $hash{$_} } @hits) {
# $_ contains the hash ref for each record
printf "%-5s %-55s %5s\n",
$_->{col1}, $_->{desc}, $_->{score};
}
|