Using if, elsif, else and unless
Perl if statements can consist of an ‘if’ evaluation or an ‘unless’ evaluation, an ‘elsif’ evaluation (yes the ‘e’ is missing), and an ‘else’ evaluation.
if
The syntax for an if statement can be arranged a few ways:
unless
The unless statement is just like an ‘if-not’. For example, the following two lines of code are equivalent:
Most commonly, you will see the following use of unless:
else
The else statement gets run when the preceding ‘if’ or ‘unless’ is not true:
Or:
elsif
If you want to check for more than one condition, you can build a larger statement using ‘elsif’:
Evaluating
The expression inside the ‘if’ condition, is evaluated. This means it is checked to see whether it is true or false. The following condition evaluates to true:
And the following evaluates to false:
The above example could also be written as:
You can also use if to check if a variable has a defined value. The following evaluates to false because $value has no defined value.
This works quite nicely with boolean values and objects, however you must be careful with strings. While the string in the following code has a defined value, it still evaluates to false:
This is because perl is not a strongly typed language. If you wanted to check if $value had a defined value, it is better to use the ‘defined’ function:
The c-style ? operator
Another way of writing an if statement is using the c-style shorthand conditional operator ?. This is very useful when assigning values. An example is:
If $flag evaluates to true, then $c will equal 4, otherwise $c will equal 5.
The form of ‘if-else’ statement can be easily embedded in other statements, for example, a print statement:
See also
To find out more, run the command: