#StoneProfitsSystem


Perl - Decision Making Statements and Loops


  • Perl conditional statements helps in the decision making, which require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

If statement:

  • The if statement has a variety of forms.

 The simplest syntax is:
if (expression)
  { true_statement_1;
     .....
  }
     true_statement_n;

  • which means that if expression is evaluated as being true then execute the block of statements.
  • In Perl, false is regarded as any expression which evaluates to 0. true any expression which is not false (non-zero).

An else may be added to provide a block of statements to be executed upon a false evaluation of the expression:
if (expression)
  {  true_statement_1;
     .....
     true_statement_n;
  }
else
  {  false_statement_1;
     .....
     false_statement_n;
  }
  • Curly braces are required for each block even if only one statement is present.
Example:


Unless Statement:
  • If you have more than one branch then the elsif can be added to the if. You cannot have an else if in Perl -- you must use elsif.
Note: The last else.

Example:

Loops:
For Statement:
The simplest is the for loop. It actually behaves like C's statement and is a little more complex.
It can do some more things.


The format of the for statement is:
for ( initialise_expr; test_expr; increment_expr )
  {
     statement(s);
  }

Example:

The While/Until Statement:
The while statement is as follows:
while (expression)
  { # while expression is true execute this block

      statement(s);
  }

Example:

ForEach Statement:
The foreach statement iterates through items in a list.
The statement has the following format:
foreach $i (@some_list)
{ # $i takes on each list item value in turn
statement(s);
}
Example:

No comments:

Post a Comment