in reply to Learning to use "each"

Just to make this either clearer or murkier (I'm not sure which, but more information is good, right? (well, sometimes))...

If you really, really want a for loop then you could do this with a C-like for loop which is not the same as the foreach loop or the foreach loop abbreviated as for. Confused yet? Either way, good! (Read it until you aren't. The confusion is the earliest stage of learning.) Let's carry on.

Take a look at this:

my %hash = ("one" => 1, "two" => 2, ); for ( my ( $key, $value ) = each %hash ; defined $key ; ( $key, $value + ) = each %hash ) { print $key . ': ' . $value . "\n"; }
That's ugly and messy, isn't it? All it's doing is setting a precondition for a couple of variables, testing the whether one of those is defined to determine whether to loop again, and updating the same variables at the end of every iteration. You could take out the defined if you want to test truthiness rather than definedness. It seems there should be a shorthand for a loop that does that all with the same variable set.

Now, look at this:

my %hash = ("one" => 1, "two" => 2, ); while ((my $key, my $value) = each %hash) { print $key, "\n"; }
Now, what three things is that loop construct doing? Read perlsyn if it's not obvious (at least the part about loop constructs).

Now, if you don't understand the differences among for, foreach/for, while, and until (not to mention do-while, do-until, and all the control modifiers like next, last, and continue) all at once, don't worry. Read perlsyn again, and play with loops.

An aside...

Then do something else, and I mean not programming... probably not anything to do with computers or even electronics, and not reading paper manuals. Garden, fish, cook, sew, or something. Then come back to it. This works on many kinds of learning.

I really like my sand garden for both this and for just general relaxation and sense of well-being. It's sand and rocks. It's never a fashion contest and it's never done so there's no deadline. It's doing for the sake of doing, almost like a kid's sandbox if you want. It can be very meditative or even spiritual if you want. You can get a little table-top one at some dollar stores, with real sand and real rocks and a real wooden rake. It's surprising how relaxing it can be, and I find I can take my mind off of nearly anything when I'm moving my sand and rocks to my whim of the moment and know I won't care where I've moved them when I leave it or come back to it.

Then, when you're ready to dive back into intricacies of syntax and semantics (or soldering, or learning a foreign language, or anything that can take concentration), doing so with a fresh look and a relaxed mood can really help.