PrevIndexNext

Conditional Statements

Branching in Perl is similar to C:
print "Name? "; $name = <STDIN>; chop $name; if ($name eq "Joe") { print "hey Joe!\n"; }
The above code asks a question ("Is the name equal to 'Joe'???). If the answer is yes, the statement(s) between the curly braces will be executed. If the answer is no, nothing will happen and execution will continue with the statement after the closing brace. Another example:
if ($name eq "Joe") { print "hey Joe!\n"; $x = 4; print "yes\n"; } else { print "nice to meet you! $x = 5; print "indeed\n"; }
Here we have multiple statements inside the braces. And there is a separate group of statements in case the answer were no (this is called the 'else clause').

Carefully note the position of the braces and the indentation. This is the "O'Reilly Standard" (and fully explained in "Perl Best Practices"). Use it. This is one of the few things about which it is a good thing to be obsessive compulsive. Indentation is most easily accomplished with the tab key. Tabs are usually set at 4. NOTE! - You should not actually put a tab character in your file. Have your editor expand tabs to spaces. Here are the needed configurations for the .exrc file for vi:

set ai ts=4 sw=4 et

Note that unlike C/C++ or Java, braces are required even if there is only one statement within the condition. If you think this is annoying, you are right and rest assured that Perl has an answer to your annoyance - but not just yet.

Here is the full conditional:

if ($name eq "Joe") { ... } elsif ($name eq "Mary") { ... } elsif ($name eq "Charlie") { ... } else { ... }
This presents a list of questions to ask. The first one to which you can answer yes is the one that is chosen. The corresponding statements will be executed and then the program will continue with the statement following the else clause.

There is no 'switch' statement in Perl as there is in C/C++. (2012 update - actually there is a switch statement as of Perl 5.10).

'if' statements can be nested as shown here:

# # get $name and $city # if ($name eq "Joe") { print "Greetings, Joe\n"; if ($city eq "Santa Cruz") { print "I live in Santa Cruz, too!\n"; } }
Perl has no limit to how deep the nesting can be. The only limit is your imagination and patience!

String Comparision Operators

In addition to 'eq' as shown above there are also these operators to ask questions inside the 'if' condition:
eq equal ne not equal gt greater than lt less than ge greater than or equal le less than or equal
This does character by character ASCII comparision just like dictionary order. Even if the things you are comparing are numbers these operators will still do a character by character comparison.

Numeric Comparison Operators

Comparing numbers is different than comparing strings:
== numeric equal != not equal > greater than < less than >= greater than or equal <= less than or equal

You must be aware of what kind of comparision you are doing!!! For example:

$x = 11; $y = 9; if ($x lt $y) { print "yes $x lt $y\n"; # this prints } if ($x < $y) { print "yes $x < $y\n"; # this does not }

Boolean Operators

There are several ways to construct a boolean:
&& and both '&&' and 'and' are used the latter is often more readable || or ! not if ($x < $y and not ($a gt $b)) { print "hah!\n"; }
The questions inside the if statements can be as complex as they need to be. If it doesn't seem to be working as you expected it to try putting in parentheses to more precisely state what you want.

How do you ask if a number is between two others? e.g. In Perl how do you ask if a number is between 1 and 10? This will not work:

if (1 <= $num <= 10) { # will give an error! ... }
You have to do this:
if (1 <= $num and $num <= 10) { ... }

True and False in Perl

One can ask whether a plain variable is true or not.
$finished = 0; $done = 1; if ($finished) { ... } if ($done) { ... }
Four things are FALSE:

Everything else is TRUE.

Again, as we noted before, Perl generally does what you want and expect it to do.

undef

Uninitialized variables appearing for the first time (not in an assignment statement) have the value of 'undef' - a perl keyword. As a string it is the same as the empty string. As a number it is treated as zero. As a logical value it is false.

Exercises

  1. Mimic a waitress taking an order in a restaurant. With certain meals you get a choice of soup or salad. With others you get choice of potato. If salad, choice of dressing. Two choices of soup. If baked potato - butter, sour cream, chives. Make it simple at first, then elaborate, if time. Print the final order in some form.

  2. Pretend you are a ticket seller at the movies. Ask the person their name and age. Children 2 and under are free, 3 through 12 is one price, teenagers another price, and seniors yet another. Everyone else pays the standard rate. Greet them and tell them what price they need to pay.

    If you accomplished that okay try a fun twist: If the person's name is "Pearl" and she is middle aged ask for the magic and secret password. If she knows it she gets in free otherwise she pays double the standard rate.

  3. For the mathematically inclined: Redo the quadratic formula exercise in the previous section. Test to see whether the value underneath the square root is negative. If so, print complex numbers as a solution. Print them with separate real and imaginary parts.

PrevIndexNext