Last week we covered conditional statements. In those, the computer checks
if the condition (the thing in parenthesis) is true, and if it is, the
code in curly braces is executed. A loop is just like a conditional
statement. However, after executing the code, we recheck the condition. If
it is still true, we execute the code again. That repeats until the
condition is false. Here is a quick example:
#!/usr/bin/perl
$x = 0;
while ($x<10) {
print "$x\n";
$x++;
}
This will print the numbers 0 through 9. Notice the new syntax, $x++. This
increments the value of $x. It is shorthand for $x = $x+1.
There is also a -- operator, which subtracts 1 from the value of the
variable.
There are a couple different kinds of loops. We will see another one later
on.
Hashes
A hash is a data structure. It has keys and values. Each key is mapped to
a value. For example, your key could be an email address and it would map
to the name of the owner of that address. The name of the owner would be
the value.
To create an empty hash, you start it with a % sign:
%hash = ();
If you want to store information in the hash, you put it in curly braces.
Interestingly, you use a $ before the name of the hash, not the % like you
use when you create it. In this example, the email address is mapped to a
name:
$hash{"bob\@example.com"} = "Bob Smith";
To retrieve a value out of the hash, you put the key name in the curly
braces. If you want to print the name of this owner, you could do it like
this:
$email = "bob\@example.com";
print "The address $email belongs to ";
print $hash{$email};
You can get a list of keys using the keys special keyword:
@listOfKeys = keys %hash;
This is most commonly used in a loop. We could loop through each key in
the hash and print the value like this:
foreach $key (keys %hash) {
print "The value is " . $hash{$key} . "\n";
}