Joe’s Notes on Perl #4 – Loops and Logic

So now we move onto loops.

Loops are what they say they are, they loop data! There are several loops, so let’s begin.

if

One of the simplest and most used loops. We want to check if something is true or not.

If loops trouble you, just say it out loud “if 10 is less than 3 print something else do something else.” Helps if you get confused.

 

unless

A less used loop, but still as valuable, unless the condition is satisfied it operates. Opposite of if.

 

while

If you are looping through lots of data and want to see if a condition is still true, like a counter, we can use a while loop.

While I’m on the subject, the reason why that line has been written as (5 <= $counter) is that if you’re not careful and type if ($counter => 5), you’ll end up setting $counter to 5. Reverse the inequality to be on the safe side.

 

for

This is a very useful loop that will give you an incremental scalar to play with. Invaluable for arrays.

foreach

foreach loops are great when you need to dump all the data from an array or hash.

Don’t forget that $cats or $keys are unavailable outside of loops!

until

Opposite of while. Executes until the condition is satisfied.

These are the major loops and logical checks.

Have fun with them in the meantime. See ya!