Perl if, else, elsif ("else if") syntax

Summary: This tutorial shows a collection of Perl if, else, and else if examples.

Here are some examples of the Perl if/else syntax, including the “else if” syntax, which is really elsif. (I wrote this because after working with many different languages I can never remember the “else if” syntax for most languages, and elsif is pretty rare.)

The Perl if/else syntax

The Perl if/else syntax is standard, I don’t have any problems here:

if ($condition1)
{
  # do something
}
else
{
  # do the 'else' thing
}

The Perl “else if” syntax (elsif)

The Perl “else if” syntax actually uses the elsif keyword. Here’s some example code that show this syntax:

if ($condition1)
{
  # do something
}
elsif ($condition2)
{
  # do something else
}
elsif ($condition3)
{
  # yada
}
else
{
  # do the 'else' thing
}

Perl’s numeric and string comparison operators

While I’m in the neighborhood of Perl and equality/comparison tests, here’s a list of Perl’s numeric and string comparison/equality operators:

                           Numeric Test      String Test
Equal                           ==                eq
Not equal                       !=                ne
Less than                       <                 lt
Greater than                    >                 gt
Less than or equal to           <=                le
Greater than or equal to        >=                ge

Not knowing the Perl has different operators for numeric tests and string tests can be a big “gotcha” when programming in Perl (so I wanted to make sure I noted this here).