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};
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link or
or How to display code and escape characters
are good places to start.