Tweet

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:

    if ($flag) { do_something() } # semi-colon optional

    if ($flag) {
        do_somthing();
    }

    do_something() if ($flag);

unless

The unless statement is just like an 'if-not'. For example, the following two lines of code are equivalent:

    if (!$flag) { do_something();}

    unless ($flag) { do_something();}

Most commonly, you will see the following use of unless:

    do_something() unless ($flag);

else

The else statement gets run when the preceding 'if' or 'unless' is not true:

    if ($flag) {
        do_something();
    } else {
        do_something_else();
    }

Or:

    unless ($flag) {
        do_something();
    } else {
        do_something_else();
    }

elsif

If you want to check for more than one condition, you can build a larger statement using 'elsif':

    if ($flag) {
        do_something();
    } elsif ($another_flag) {
        do_another_thing();
    } else {
        do_something_else();
    }

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:

    my $value = 1;
    if ($value == 1) {}

And the following evaluates to false:

    my $value = 0;
    if ($value == 1) {}

The above example could also be written as:

    my $value = 0;
    if ($value) {}

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.

    my $value;
    if ($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:

    my $value = "0";
    if ($value) {}

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:

    my $value = "0";
    if (defined($value)) {}

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:

    my $c = ($flag) ? 4 : 5;

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:

    print "I have ", ($pets) ? "a pet" : "no pets", "\n";

See also

To find out more, run the command:

    perldoc perlsyn
[Top]