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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
use strict;
my $cat = "Socks";
#Simple equality check
if ($cat eq "Socks") {
print "Yes! Joe's cat is called Socks!\n";
}
#Numerical with an else statement
if (10 < 3) {
print "Yes, for some reason 3 is less than 10!\n";
} else {
print "All is right in the world\n";
}
#String checking
if ("Hello" eq "Hello") {
print "Hello is equal to Hello\n";
}
|
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.
1
2
3
4
5
6
7
|
use strict;
unless (10 == 3) {
print "10 does not equal 3\n";
} else {
print "The world is broken\n";
}
|
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
use strict;
my $counter = 0;
while ($counter <= 5) {
   print "The counter is at $counter\n";
   $counter++;
}
#Remember the syntax for greater than or equal to!
if ($counter >= 5) {
   print "Counter is over 5!\n";
}
#It is safer to write this line as:
if (5 <= $counter) {
   print "Counter is over 5!\n";
}
|
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.
1
2
3
4
5
6
7
8
9
10
11
12
|
use strict;
my $cats = 4;
#When there are more than 4 cats stop
for (my $i = 1 ; $i <= $cats; $i++) {
   print "There are $i cats now!\n";
}
#Prints each element of an array
my @array = qw ( Socks Poppy Milly);
for (my $i =0 ; $i<@array ; $i++) {
   print $array[$i]."\n";
}
|
foreach
foreach loops are great when you need to dump all the data from an array or hash.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
use strict;
#Arrays
my @array = qw ( Socks Poppy Milly);
foreach my $cats (@array) {
print $cats."\n";
}
#Hashes
my %hash = ("Joe" => "Socks", "Matt" => "Poppy", "Pete" => "Milly");
foreach my $keys (keys %hash){
print "Keys: $keys Values: $hash{$keys}\n";
}
|
Don’t forget that $cats or $keys are unavailable outside of loops!
until
Opposite of while. Executes until the condition is satisfied.
1
2
3
4
5
6
7
8
|
use strict;
my $counter = 0;
until ( 10 < $counter) {
print "Counter is not over 10 yet!\n";
$counter++;
}
print "Counter is now $counter\n";
|
These are the major loops and logical checks.
Have fun with them in the meantime. See ya!