Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pulling First 20 Items from a Sorted Array

Status
Not open for further replies.

uuallan

ISP
Feb 5, 2002
4
US
Hi all,

I have a perl script that searches through files in a directory, and creates an array based on that information.

After the array is created, I sort the data based on one of the variables:

@av_sorted=sort { $av_data{$a} <=> $av_data{$b} } %av_data;

Then I put all of the data into a variable, which can be printed:

foreach (@av_sorted) {
if ($av_data{$_} ne &quot;&quot;) {
$servername=$_;
$avdata=$av_data{$_};
$html_output.=&html_servers_td();
$html_output.=$deathfile{$_};
$html_output.=&html_avdata_td();
}

}

The problem I have is that I want to pull out only the top 20 entries from the array. I thought I could do it by changing the foreach line to:

foreach (@av_sorted[0..19) {

But no data is returned, when I add that line. I don't get any errors, but no data is returned.

I didn't want to post the whole script here, as it is rather long, but if you need more information to assist me, I would be happy to post it all.

What would be the best way to pull out just the top 20 entries?





 
Do you want @av_sorted to contain the keys or the values of the %av_data hash? The way that you have written it, you are passing the keys AND the values through the sort so all of your values are getting sorted like
Code:
$av_data{$valueA} <=> $av_data{$valueB}
Since the values of the hash aren't existing keys they are automagically created and sorted (Their value being zero since you are sorting in a numerical context). So all the values are probably getting sorted to the front of the array.

What you probably meant to do was

@av_sorted=sort { $av_data{$a} <=> $av_data{$b} } keys %av_data;

which sorts the keys based on their value and dumps the sorted keys into @av_sorted. Then your
Code:
foreach (@av_sorted[0..19]) {
should work. (I assume that the missing ']' in your original post is a typo).

Incidently, if you were using warnings (a '-w' at the end of the shebang line) then you would probably get a 'Use of uninitialized value in numeric comparison (<=>)' error.

jaa
 
Doh! I should have caught that...thanks for your help, that fixed it right up :).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top