Loops in Perl – Pt. 1

In previous tutorials we discussed the various data types and a few brief looping examples. In Perl we can execute a portion of code any number of times we specify or we can execute a portion of code whether our given test succeeds or fails. Many times in our applications we want to test the accuracy of given information, the most common would be a password checker.

IF/ELSE/ELSIF

These three aren’t really loops, they are actually iterations meaning it will only be run one time- and one time only.  A loop is something that runs over a particular piece of code more than one time, but these are widely accepted and considered as loops and people will understand what you mean if you refer to them as so.

my $password = “test”;
if ($password eq “test”)
{
print “Our password was test”;
}

Our small example above shows a simple test conditional test.  IF $password EQUALS test { … }. We are testing our variable $test to see if it contains the exact string “test”.  If our test passes, everything inside the { and } will be executed.  You can print statements like we did, do mathematical equations, redirect the user to a new page, store cookies, etc.  You can do as many or as little as you want, you can print out 100 different lines of code, but whatever you do.. it will only execute if our test succeeds.

Everything between the ( )’s is the test, everything between the { } is what will happen depending on whether it passes or fails.

In our example, we only printed information if our password equaled test and nothing happened if it didn’t.  Running this program with a wrong password wouldn’t produce any information making the end user think the script crashed.  Let’s print out a message if the password is wrong so they know what happened.

my $password = “test”;
if ($password eq “test”)
{
print “Our password was test”;
}
else
{
print “The password you entered was incorrect”;
}

What we did was add an else clause after our end bracket in if.  We don’t need to setup a second test since IF and ELSE work in conjunction with one another.  If for whatever reason the test fails, everything in the else { } will be executed.  Let’s now change the above example to intentionally fail on us so we can catch the else.

my $password = “test”;
if ($password eq “jello lollipop”)
{
print “Our password was test”;
}
else
{
print “The password you entered was incorrect”;
}

Simply put, we are testing to see if our password that has been assigned the value “test” is equal to “jello lollipop”.  It should go without saying two values are different and this will fail and print: The password you entered was incorrect.

ELSIF:
Some times an IF/ELSE isn’t enough control over the content of our tests.  Let’s say for example we want to check to see if someone knows your name and cna type it in, in either all caps or all lowercase letters.

#### $guessed_name is assuming you have one setup already, we didn’t create it here
if ($guessed_name eq “sulfericacid”)
{
print “You got my name right!”;
}
elsif ($guessed_name eq “SULFERICACID”)
{
print “You still got my name right!”;
}
else
{
print “Ooops, you don’t know my name afterall”;
}

Our snippet above is really doing two tests. If the first test if(…) doesn’t succeed, the elsif will be given a turn.  In our example, pretend $guessed_name equals “SULFERICACID”.  The elsif will catch on and say: “You still got my name right!” even though the initial test failed.  Now, if my name equaled “SulfericAcid” both the tests would have failed and else would have kicked in and printed out our little error message.

Elsif requires a second test in parenthesis because it is given the chance to see if a different piece of information returns true, Else doesn’t require a seperate test because this happens if nothing else works.


Unless

This is virtually an inverted If construct.  Insted of executing code if the returned test proves to be true, our code is only processed if it comes back false.

my $guessed_name = “SulfericAcid”;
unless ($guessed_name eq “sulfericacid”)
{
print “You apparently don’t know my name!”;
}

In simple terms, this is really saying “If $guessed_name does NOT equal sulfericacid, do the following”.  Regardless of what $guessed_name really was, if it’s not exactly “sulfericacid” the code will be executed and you’ll be yelled at for not knowing my name.  So unless the test is true, the code will be proccessed.


For

A for loop lets you execute a chunk of information or processes that fit your given pattern.  Let’s say we wanted to impress people in our school and show them we know how to count in Perl, but we don’t want Perl to count endlessly..we’ll need some way to stop the loop.

For loops are an excellent way to run over a certain piece of code any number of times you want.  In the example below, we are counting from 1-20.

my $number = 0;
for (1 .. 20)
{
$number++;
print “I can count: $number\n”;
}

We are using a range operater in our loop; a range operator is a number .. number as you can see beween our parenthesis.  This means for these numbers, 1-20, do the following code.  In the end, it will process whatever we asked it to exactly twenty times (1-20 is 20 numbers).

The rest of the script should look pretty familiar to you now.  We’re setting our variable $number to zero before our loop, then each time our loop goes through it will add +1 to the current number nad print it back to the screen.

You don’t necissarily have to use positive numbers, the rance ( -10 .. -1) will loop exactly 10 times and will produce our numbers from the last script accurately.

Now, because programmers typically like to condense code as much as possible, you can shrink the number of lines in our last example down some.  This is one of those things that may be confussing for you until you get the chance to play with them a few times in your scripts.

#!/usr/bin/perl

for (my $number = 1; $number <=20; $number++)
{
print “I can count: $number\n”;
}

This alternative method is taking three expressions.  Each expression is separated by a semicolon and this is virtually doing the exact same thing as our previous example.  Only difference is we’re doing all the calculations and variable settings inside the for loop parenthesis rather than before and inside the squirrlie brackets.

We are setting our variable in expression 1, in our case we set this to the number 1 for simplicity.  The second expressesion acts almost like a while loop which we haven’t learned yet.  While the current $number is less than or equal to the number 20, we will do whatever is in expression 3 and run our code between the { }.  We have to autoincrement $number in expression 3 otherwise $number would never get incremented and we’d be tossed into an endless loop.

And endless loop is something we all fear, it’s a loop that begins but will not stop.  This happens typically by a misjudgement in our coding, but there are times were you’ll intentionally do such a thing.  A really quick example of an endless loop is:

my $number = 1;
while ($number == 1)
{
print “This is the string that never ends!!\n”;
}

Foreach

The foreach loop is the one I use most often as it’s a very handy tool while debugging your scripts whether they be in Perl or CGI.  This will loop over every item in an array or a hash and allow you to print or manipulate the data in any way you wish.

my @array = (“Minnesota”, “Iowa”, “Wisconsin”, “California”)’

foreach(@array)
{
print “$_\n”:
}

We are pulling in a list of information from our @array and executing them one at a time.  Remember that whatever you do with your code inside of a foreach will be applied to every item it comes by.  We are printing each array element using $_, notice we only have to include one print statement for each of them to print to screen at run time.

This is what makes this such a powerful tool.  It lets you print full arrays and full hashes quickly and easily. What you wish to do each time it finds a piece of information is up to you, but to keep simplicity all we did was print them.

Let’s try an example using a hash now.

my %hash = (“Minnesota” => “1”, “Iowa” => “2”, “Wisconsin” => “3”, “California” => “4”);

foreach (keys %hash)
{
print “$_ => $hash{$_}\n”;
}

This isn’t much different than printing an array but we’re using keys inside the foreach ().  If you want to learn more about arrays and hashes, please see the other tutorials written on these datatypes.


Other important information

There are more looping structions which will be included as a second part to this tutorial in the future.  This discusses the more basic and most common ones and should help you grasp a better understanding of how loops work and why we’d want to use them.

If you are trying to compare two strings to see if they are identical, you’d use eq such as:

my $name = “sulfericacid”;

if ($name eq “sulfericacid”)
{
print “You know my name!”;
}

If you were trying to see if a variable had the value of a number, you use == (a double equal sign)

my $number = “4”;

if ($number == “4”)
{
print “Correct!!”;
}

Keep in mind we are testing values, if you tried to use a single = sign the script would fail.  A = is an assignment operator, it assigns the value to the right.  eq and == are comparison operators, they see if they match up but won’t assign the value.

Author: Syperder Co
I waltzed into the Web Design community as a professional when I was just 15 years of age founding SpyderWebDesigns. Through the years my interests shifted from web development to backbone and user interaction.In 2000 Sulfericacid.com was born. The world’s largest free and 100% ad-free web site where you could use and download 24 Perl and CGI script along with tutorials without limits or restrictions. January 2005 the site was renamed to SpyderScripts.com as a subsidy of SpyderCo.

In 2001 I also founded an SEO company SpyderSubmission.com. We’ve helped nearly 2300 web sites achieve higher rankings than they ever could have imagined since our launch four years ago.

On a more personal note, I’ve attained 28 certifications from BrainBench.com and about 40 certifications in total from all resources. One of these is a near Masters in Perl which ranks second highest test score in the state and 17th throughout the country.

I have a Perl Abbot status on PerlMonks.org working on getting my Perl Saint status this fall.