Flylib.com

Books Software

 
 
 

Conditional Statements: ifelse and unless


Conditional Statements: if/else and unless

Perl offers two conditional statements, if and unless , which function opposite one another. if enables you to execute a block of code only if certain conditions are met so that you can control the flow of logic through your program. Conversely, unless performs the statements when certain conditions are not met.

The following sections explain and demonstrate how to use these conditional statements when writing scripts for Linux.

if

The syntax of the Perl if / else structure is as follows :

if (condition) {
  statement or block of code
} elsif (condition) {
  statement or block of code
} else {
  statement or block of code
}


condition can be a statement that returns a true or false value.

Truth is defined in Perl in a way that might be unfamiliar to you, so be careful. Everything in Perl is true except (the digit zero), "0" (the string containing the number ), "" (the empty string), and an undefined value. Note that even the string "00" is a true value because it is not one of the four false cases.

The statement or block of code is executed if the test condition returns a true value.

For example, Listing 27.3 uses the if / else structure and shows conditional statements using the eq string comparison operator.

Listing 27.3. if/elsif/else
if  ($favorite eq "chocolate") {
      print "I like chocolate too.\n";
} elsif ($favorite eq "spinach") {
      print "Oh, I don't like spinach.\n";
} else {
     print "Your favorite food is $favorite.\n";
}

unless

unless works just like if , only backward. unless performs a statement or block if a condition is false:

unless ($name eq "Rich")        {
  print "Go away, you're not allowed in here!\n";
}


Note

You can restate the preceding example in more natural language like this:

print "Go away!\n" unless $name eq "Rich";





Looping

A loop is a way to repeat a program action multiple times. A very simple example is a countdown timer that performs a task (waiting for one second) 300 times before telling you that your egg is done boiling.

Looping constructs (also known as control structures ) can be used to iterate a block of code as long as certain conditions apply, or while the code steps through ( evaluates ) a list of values, perhaps using that list as arguments.

Perl has four looping constructs: for , foreach , while , and until .

for

The for construct performs a statement (block of code) for a set of conditions defined as follows :

for (start condition; end condition; increment function) {
  statement(s)
}


The start condition is set at the beginning of the loop. Each time the loop is executed, the increment function is performed until the end condition is achieved. This looks much like the traditional for / next loop. The following code is an example of a for loop:

for ($i=1; $i<=10; $i++) {
      print "$i\n"
}


foreach

The foreach construct performs a statement block for each element in a list or array:

@names = ("alpha","bravo","charlie");
foreach $name (@names) {
  print "$name sounding off!\n";
}


The loop variable ( $name in the example) is not merely set to the value of the array elements; it is aliased to that element. That means if you modify the loop variable, you're actually modifying the array. If no loop array is specified, the Perl default variable $_ may be used:

@names = ("alpha","bravo","charlie");
foreach (@names) {
  print "$_ sounding off!\n";

}


This syntax can be very convenient , but it can also lead to unreadable code. Give a thought to the poor person who'll be maintaining your code. (It will probably be you.)

Note

foreach is frequently abbreviated as for .


while

while performs a block of statements as long as a particular condition is true:

while ($x<10) {
     print "$x\n";
     $x++;
}


Remember that the condition can be anything that returns a true or false value. For example, it could be a function call:

while ( InvalidPassword($user, $password) )        {
        print "You've entered an invalid password. Please try again.\n";
        $password = GetPassword;
}


until

until is the exact opposite of the while statement. It performs a block of statements as long as a particular condition is falseor, rather, until it becomes true:

until (ValidPassword($user, $password)) {
  print "You've entered an invalid password. Please try again.\n";
  $password = GetPassword;
}


last and next

You can force Perl to end a loop early by using a last statement. last is similar to the C break commandthe loop is exited. If you decide you need to skip the remaining contents of a loop without ending the loop itself, you can use next , which is similar to the C continue command. Unfortunately, these statements don't work with do ... while .

On the other hand, you can use redo to jump to a loop ( marked by a label) or inside the loop where called:

$a = 100;
while (1) {
  print "start\n";
  TEST: {
    if (($a = $a / 2) > 2) {
      print "$a\n";
      if (--$a < 2) {
        exit;
      }
      redo TEST;
    }
  }
}


In this simple example, the variable $a is repeatedly manipulated and tested in an endless loop. The word start will only be printed once.

do ... while and do ... until

The while and until loops evaluate the conditional first. The behavior is changed by applying a do block before the conditional. With the do block, the condition is evaluated last, which results in the contents of the block always executing at least once (even if the condition is false). This is similar to the C language do ... while ( conditional ) statement.