logo

internet.com
Join the free
WDVL newsletter!

home

Using the if, elsif, else and unless Control Statements

Using the if, elsif, else and unless Control Statements

  • The most common control statement used in CGI scripts is the "if" test. The if test checks to see if some expression is true, and if so, executes the routines in the statement block. Perl uses a simple binary comparison as a test of truth. If the result of some operation is true, the operation returns a one and the statement block is executed. If the result is false, it returns a zero, and the statement block is not executed. For example, consider the following code:

    if ($name eq "Selena Sol")
           {
           print "Hello Selena.\n";
           }
    

  • In this example, Perl checks to see if the scalar variable $name has the value of "Selena Sol". If the patterns match, the matching operation will return true and the script will execute the print statement within the statement block. If Perl discovers that $name is not equal to "Selena Sol" however, the print will not be executed.

Be careful with your usage of "eq" versus "=". Within an "if" test, if you write $name = "Selena Sol", you will actually be assigning "Selena Sol" to the variable $name rather than comparing it to the value "Selena Sol". Since this action will be performed successfully, the if test will always test to true and the statement block will always be performed even if $name did not initially equal "Selena Sol".

  • The if test also provides for alternatives: the "else" and the "elsif" control statements. The elsif alternative adds a second check for truth and the else alternative defines a final course of action for every case of failed if or elsif tests. The following code snippet demonstrates the usage of if, elsif, and else.

    if ($name eq "Selena Sol")
           {
           print "Hi, Selena.\n";
           }
         elsif ($name eq "Gunther Birznieks")
           {
           print "Hi, Gunther\n";
           }
         else
           {
           print "Who are you?\n";
           }
    

  • Obviously, the else need not perform a match since it is a catch-all control statement.

  • The "unless" control statement works like an inverse "if" control statement. Essentially it says, "execute some statement block unless some condition is true". The unless control statement is exemplified in the code below:

    unless ($name eq "Selena")
           {
           print "You are NOT Selena!\n";
           }
    

Additional Resources:

Statement Blocks
Table of Contents
foreach

Up to => Home / Authoring / Scripting / Tutorial

Instantly look up a "techie" word using Webopedia!!


internet.com
e-commerce
WebDeveloper Network



Copyright 1999 internet.com Corporation. Legal Notices. Privacy Policy.

www.internet.com