If only...
- if statements have the form
of:
if ($garfield == 6) {
print "Garfield is most definitely six\n";
}
- The bolded code is the control structure. Everything {
between the curly braces } will be executed if the condition ($garfield
== 6) is true.
$popcorn = 10;
if ($popcorn == 10) { }
if ($popcorn < 15) { }
if ($popcorn != 1) { }
if ($popcorn eq "10") { }
if ($popcorn = 15) { } #Huh?
$behavior = "music";
if ($behavior eq "music") { }
if ($behavior = "mon ami") { } #Same as last odd one...
if ($behavior =~ /music/) { } #Huh?
if (length($behavior == 5) { } #What?
- And some things it thinks are false:
if ($popcorn == 5) { }
if ($popcorn eq "dancing") { }
if ($behavior ne "music") { }
- So far all of the conditions have been comparisons of some sort: greater
than, less than, is equal to, is equivalent to, matches. The exceptions of
course were the assignements ($popcorn = 15) and ($behavior = "mon ami").
Why were these true? Consider this: Perl also considers the following condition
true:
if (1) { } #True!
if (0) { } #False!
- Remember: Computers are dumb. For a computer true just means "anything
that's not 0" and false means "0". ($popcorn = 15) is true
because it's 15, which is not 0. ($behavior = "mon ami") is true
because it's "mon ami", which is not 0. However, ($popcorn = 0)
would be false, because it's 0.
$popcorn = 10;
if ($popcorn == 15) {
print "Popcorn is 15";
}
else {
print "What? Popcorn isn't 15??";
}
- The statements enclosed in the else's curly braces execute if the preceding
if's condition evaluates as false. If the if is true, the else does nothing.