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

Summary: A collection of Perl if, else, and else if examples.

Here's a quick demo 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)

In Perl the "else if" syntax actually uses the elsif keyword. Here's some example code showing 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 tests (comparisons), 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.

Limits to elsif

Now that I finally got it spelled right (no second "e") i am having a problem with the code. Is there a limit to how many elsif statements you can have below one if? I can't seem to find any doco on this that shows a limit but my code quits working at the 3rd elsif.

Any help would be appreciated. Thanks!

I'm not aware of any limits

I'm not aware of any limits on the number of elsif statements you can have, but there may be one in the hundreds or thousands. FWIW, I just created this code, and it works fine with four elsif clauses:

$foo = 'a';

if ($foo eq 'b') {
  print('got a b');
}
elsif ($foo eq 'c') {
  print('got a c');
}
elsif ($foo eq 'd') {
  print('got a d');
}
elsif ($foo eq 'e') {
  print('got a e');
}
elsif ($foo eq 'f') {
  print('got a f');
}
else {
  print('hit the "else" clause');
}

FWIW, as a test, I also removed the 'else' statement, and this code worked fine. If you can share any more specific information I'll be glad to see if I can help.

Post new comment

The content of this field is kept private and will not be shown publicly.