in reply to Tutelage, part two

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."

Replies are listed 'Best First'.
Re: Re: Tutelage, part two
by ctp (Beadle) on Jan 05, 2004 at 00:36 UTC
    Thank you for the code snippet, and the advice.

    I basically just started learning Perl, and I have found that I am of two minds on the use of strict; as a beginner. I now have a script that works, and will get me a good grade - for the beginner's assignment at hand. When I turn on strict; I get several lines of admonishment...yes, very important admomishment, I know...but I also have no output to see if I am even headed in the right direction, and strict; tells me a bunch of new stuff I don't understand on top of it all. I am barely at the point of remembering which part of a hash is the key and which is the value, and I'm just now barely figuring out how $hash{$_}++ does what it does :-D

    What I have taken to doing is putting in strict; and then commenting it out until I want to hear from it. As I learn more I know I will want to hear from it all the time, but for now I'm happy that a simple foreach loop even works as written.

    Thanks again!
      Here's the cheat sheet on strict. Declare global variables with our() (or declare them up at the top with 'use vars ...'. and everything other variable with my(). The rest of strict's functions will stop you from writing bugs so if you run into other things then your code is already incorrect.
      use vars ( '$SOME_GLOBAL' ); $SOME_GLOBAL = 42; our $ANOTHER_GLOBAL = 'fnord'; sub a_function { # A variable declared just for the inside of a_function. my $some_param = shift; print "$some_param\n"; }