Perl, lesson 4
Programs need to choose: charge shipping only on small orders, warn when a battery is low.
In Perl you make that choice with if.
The condition goes in parentheses and the body in braces. The braces are required, even
for one line. For more cases, add elsif branches (spelled without an "e" in the middle):
Perl checks the conditions from top to bottom and runs only the first branch that matches.
Because a scalar can be a number or a string, Perl has two sets of comparison operators. The symbols compare as numbers; the letter words compare as strings:
| Numbers | Strings | Meaning |
|---|---|---|
== | eq | equal |
2 exercises to try what you just read.
!= |
ne |
| not equal |
< | lt | less than |
> | gt | greater than |
<= | le | less or equal |
>= | ge | greater or equal |
Using the wrong one is a classic Perl bug. "abc" == "xyz" is true, because both strings
count as the number 0 (and use warnings will complain). Compare names with eq, amounts
with ==.
&& (and), || (or) and ! (not) combine conditions. Perl also has the words and, or
and not, which mean the same thing but bind more loosely; they are mostly used between whole
statements, as in open(...) or die. Inside a condition, the symbols are the safer choice.
Both && and || short-circuit: the right side runs only if it's needed.
These values are false: 0, the string "0", the empty string "", and undef.
Everything else is true, including "0.0" and "00".
unless is the opposite of if: the block runs when the condition is false. It reads well
for simple checks, but avoid unless ... else, which is hard to follow.
For a single statement, Perl lets you put the condition after it. This is very common:
condition ? a : b picks one of two values in an expression:
Read a whole-number temperature in Celsius and print one word describing it:
freezingcoldmildhotSample input:
Sample output:
A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap
years only if they are also divisible by 400. Read a year and print either
<year> is a leap year or <year> is not a leap year.
Sample input:
Sample output:
my $battery = 12;
if ($battery < 20) {
print "Low battery!\n";
print "Plug in soon.\n";
}
else {
print "Battery OK\n";
}if ($score >= 90) { print "A\n" }
elsif ($score >= 80) { print "B\n" }
else { print "C or below\n" }unless ($is_open) {
print "Closed\n";
}print "Free shipping!\n" if $total >= 50;
print "Closed\n" unless $is_open;my $fee = $total >= 50 ? 0 : 5;18mild20242024 is a leap year