The Perl Conference Salt Lake City 2018 Banner

The conditional (ternary) operator

One way to reduce the verbosity of Perl code is to replace if-else statements with a conditional operator expression. The conditional operator (aka ternary operator) takes the form: logical test ? value if true : value if false.

Let’s convert a standard Perl if-else into its conditional operator equivalent, using a fictitious subroutine. First here is the if-else:

sub calculate_salary {
    my $hours = shift;
    my $salary;
    if ($hours > 40) {
        $salary = get_overtime_wage($hours);
    }
    else {
        $salary = get_normal_wage($hours);
    }
    return $salary;
}

And here is the same statement using the conditional operator:

sub calculate_salary {
    my $hours = shift;
    return $hours > 40 ? get_overtime_wage($hours) : get_normal_wage($hours);
}

Hopefully this example shows how using the conditional operator can shorten and simplify Perl code. For further detail, check out the official documentation.


This article was originally posted on PerlTricks.com.

Tags

David Farrell

David is the editor of Perl.com. An organizer of the New York Perl Meetup, he works for ZipRecruiter as a software developer.

Browse their articles

Feedback

Something wrong with this article? Help us out by opening an issue or pull request on GitHub