ritz0 has asked for the wisdom of the Perl Monks concerning the following question:

I have made a perl script that sorts through a hotline log, grabs the name of the file that was downloaded, writes the name to the key of a hash, then writes the count to the hash value. When it's done counting, the script then generates the start of an html page and a table. Inside that, the script loops through the values and keys spitting out the necessary <tr> tags. Finally, it closes the table and closes the html tags. Below is just the loop from my script that generates the individual table entries. (I had to take out a lot of the HTML tags so it would be accepted.)
foreach $key (sort {$freqpage{$b} <=> $freqpage{$a}} keys %freqpage)
	{
	    print HOTFILES "$freqpage{$key}\n"; 
	    print HOTFILES "$key \n"; 
	}

Everything works great except when it's done I have an HTML page with ~1800 table entries. I'd like to trim this list down to just the top 20 files downloaded instead of a 900k download/redraw hell page. How do I limit foreach? I think using a while() or for() wouldn't work because one iteration would still trigger the aforementioned foreach() loop that would *then* go through all the files. I'm out of ideas. Anyone have a suggestion?

Replies are listed 'Best First'.
Re: Limits on a foreach loop
by Crulx (Monk) on Feb 04, 2000 at 00:34 UTC
    You need to simply break out of the foreach loop you are in Something like the following would work fine.
    $i = 0; foreach $key (sort {$freqpage{$b} <=> $freqpage{$a}} keys %freqpage) { print HOTFILES "$freqpage{$key}\n"; print HOTFILES "$key \n"; if($i++ > 20) { last } }
    Good luck.
    Crulx crulx@iaxs.net