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


David Farrell

David is a professional programmer who regularly tweets and blogs about code and the art of programming.

Browse their articles


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