btw - yes, we have already covered that I should be using strict; and declaring my variables, that I should really be slurping my text file (although the script currently does what it should thru some kludgy perl magic ;), and a few other things I need to fix before I turn it in. :-)
The fundamental change that you need to make to become a good Perl prgrammer (and a good programmer in general), is that you have to use strict
before you code, and declare your variables
as you write them, not at the end.
You are driving blind. When things don't work, you don't know why. With use strict, 90% of all your errors will be caught by the compiler. Why make things harder on yourself?
As for the problem at hand, you don't need two loops, you need one, but you need to exit the loop when you have gone through it 10 times. Try:
my $ctr=1;
foreach $key (sort {$hash{$b} <=> $hash{$a}} keys %hash) {
print "$key\t\t= $hash{$key}\n";
last if $ctr++ == 10;
}
last tells the interpreter to exit the loop unconditionally.
-pete
"Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere."
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.