Comparison Operators
Since most conditional switching is based on comparing the values of two variables, we first need to know how to do those comparisons. Perl provides two sets of comparison operators—one set for comparing numeric values, another set for comparing string values.
| Comparison | Numeric Operator | String Operator |
|---|---|---|
| Equals | == |
eq |
Does Not Equal | != |
ne |
Is Greater Than | > |
gt |
Is Greater Than or Equal To | >= |
ge |
Is Less Than | < |
lt |
Is Less Than or Equal To | <= |
le |
Perl does not define a boolean (true/false) data type. Instead, the comparison operators return 1 if the comparison is true and undef if false. undef, short for “undefined”, is a special value that is treated as 0 when used in a numeric context and "" (the empty string) when used in a string context.
Logical Operators
The logical operators, and and or are used to evaluate multiple conditions simultaneously. $a and $b evaluates to true if $a and $b each individually evaluate to true, and evaluates to false otherwise. $a or $b evaluates to true if at least one of $a and $b individually evaluates to true, and evaluates to false only if both individually evaluate to false. and and or can also be represented symbolically as && and ||, respectively.
The logical operator not is used to reverse the value of the condition it precedes. So not $a is false if $a is true, and true if $a is false. not can also be represented symbolically as !.
A Word on Truth and Falsity
As mentioned in the discussion of comparison operators, Perl does not define explicit true and false values. For the purposes of logical operations, the following values are treated as false:
All other values are treated as true.
Note that in the above, # introduces a single-line comment: everything after the # until the end of the line is ignored by the Perl interpreter. Also note that '0' evaluates to false. This is because of the implicit conversion from string to numeric values mentioned in the previous post.
Conditional Statements
Conditional Statements Generally
Conditional statements test the truth or falsity of a condition and, if the condition evaluates to the desired truth or falsity, execute the code in the following block. Code blocks in Perl begin with { and end with }. The conditional statement must always be followed by a code block, even if there is only one line of code to be executed if the condition evaluates to the desired truth value. So
is a syntax error: unlike in languages such as Java and C++, this code must be written as
even though there is only one line of code that is dependent on the conditional.
if and unless
The two simplest conditional statements are if, which executes the block of code that follows it if the given condition is true, and unless, which executes the block of code that follows it if the given condition is false (so unless ($foo) is the same as if (not $foo)). So, for example,
produces the output
In this simplest case of an if or unless that is used to execute a single statement, and does not have an attached else or elsif clause (we’ll discuss those in a moment), we can avoid having to create a code block by placing the if or unless after the statement we want executed. So the following program is the exact same as the one above:
else and elsif
An else clause can be placed after an if or unless statement, and the code in the else clause is executed if the code in the if or unless is not. So
once again produces the output
To chain two or more conditions together in this way (if the first condition isn’t fulfilled, check the second condition and execute its code if it is fulfilled, otherwise check the next condition, and so on and so forth until some code is executed if none of the conditions are fulfilled), the conditions after the first are stated using the keyword elsif (there is no elsunless— to get that behavior, you would have to nest an unless clause inside an else block). So, for example,
produces the output foo is medium. Note that a final else clause is not required; if it is absent, the program will simply do nothing if none of the conditions are fulfilled. So, for example,
produces no output because neither of the conditions were fulfilled. Also note that the fulfilling of one condition meets that the following conditions are not checked. For example, if the value of $foo in the above program were 3, the program would produce the output foo is small. It would not also print foo is medium, even though $foo < 10 is true, because as soon as one of the conditions is fulfilled, the rest of the if-elsif-else chain is bypassed.
Digression: Hashes
A hash is a built-in data type in Perl that associates keys with values. For example, a hash might be used like a contacts list to associate names with email addresses. Hash variables are declared using the sigil %. The listing of the hash’s contents is bounded by parentheses. Keys are separated from values using the so-called “fat comma” operator, =>, and key-value pairs are separated from each other by commas. For example,
When accessing the values in a hash, the name of the hash variable is prefixed by the sigil $ for a scalar (since the value that is eventually retrieved is a scalar), followed by the name of the key enclosed in curly braces { }. For example, using the hash declared above, print $contacts{"Joe Smith"}; produces the output jsmith@aol.com.
The builtin function exists can be used to check whether a hash contains a value for a particular key. Still using the hash declared above, exists $contacts{"Paul Williams"} would evaluate to false, since %contacts does not contain a value for the key "Paul Williams".
Using Hashes as an Alternative to Extended if-elsif-else Chains
Suppose we want to write a program that takes as input from the user a number between 1 and 10, inclusive, and prints out that number as a word. We could use an if-elsif-else chain: first check if the user input 1, then check 2, then 3, and so and so forth until an error message is printed if the user’s input isn’t a number 1-10. But this long of a chain can get cumbersome very quickly. Is there any way to shorten the code? Yes—we use a hash to associate the numbers with their corresponding words. The code for this program looks like this:
We see two new elements in this code. First, <STDIN> is an instruction to get input from the keyboard. The user types their input into the console and presses Enter to submit. Unfortunately for the programmer, the user pressing Enter to submit causes a newline character to be appended to the input string that is stored to $userInput. This is where the second new element comes in. The chomp function strips the trailing newline and stores the result back to the same variable. So, for example, if the user inputs 7, the program runs as follows:
if and elsif blocks in the chain. What would have been the else clause is handled by the unless exists check. For example, if the user enters 13, the program runs as follows:
The program checks to see whether %numbersSpelledOut contains a value for the key 13 and, finding that it does not, prints the error message.
The Ternary Conditional Operator
One of the more common uses of conditionals is to set variables. For example, the following code sets $max to the larger of $a and $b:
The ternary conditional operator can be used to shorten this if-else construct to a single statement. It is written as $testCondition? $valueIfTrue : $valueIfFalse. So the above example could be rewritten as
An unusual feature of Perl is that it allows the ternary conditional to be used on the left side of an assignment operator to determine which variable a value is to be assigned to. For example, this program assigns the larger of $a and $b to $max and the smaller of the two values to $min:
The defined function used in the last line of this code snippet checks whether a value has been assigned to the specified variable.
I've never seen anything like the terminary conditional operator before. Is there any way to chain them together like there is with if-else statements?
ReplyDeleteYes. You could just put another ternary conditional as the value if false. So for example, you might do something like $foo = ($a > $b)? $a : ($b > $c)? $b : $c;
DeleteDoes perl support bitwise operators? If so what is the syntax?
ReplyDeleteYes. & for bitwise AND, | for bitwise OR, ^ for bitwise XOR, ~ for bitwise NOT, << and >> for bitwise left shift and right shift, respectively.
Delete