Support Forums

Full Version: Pearl elseif construction
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How to create a proper if/elseif construction

Code:
#!/usr/bin/perl

# HTTP HEADER
print "content-type: text/html \n\n";

# SOME VARIABLES
$x = 7;
$y = 7;

# TESTING...ONE, TWO...TESTING
if ($x == 7) {
    print '$x is equal to 7!';
    print "<br />";
}
if (($x == 7) || ($y == 7)) {
    print '$x or $y is equal to 7!';
    print "<br />";
}
if (($x == 7) && ($y == 7)) {
    print '$x and $y are equal to 7!';
    print "<br />";
}

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




Code:
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:

Code:
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:
Code:
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.