Home / code / cgi

Flow control

First you have the operators:

Then you have the statements:

 

Mathematical operators

Operator calculation example
+ add 3+3
- minus 3-1
* multiply 3*3
/ divide 3/3

Compare operators

Operator calculation example
Number String    
== eq equals $string eq "tom"
!= ne is not equal $string ne "tom"
> gt is larger then $number > 20
< lt is smaller then $number < 20
>= ge is larger then or equal $number >= 20
<= le is smaller then or equal $number <= 20

Logical operators

Operator Description Example
|| Logical OR $number1 > 20 || $number2 < 20
&& Logical AND $number1 > 20 && $number2 < 20
! Logical NOT ! $number1 > 20

IF statement

Well you know, if works as follows: if the statement is true, then this happens, when it is false, that happens.

print "how old are you?";

chomp ($age =<STDIN>);

if '$age < 18)
{
  print "Sorry, you're not old enough!";
}
else
{
  print "You're old enough to enter";
}
The else part is optional.
print "How old are you?";

chomp ($age =<STDIN>);

if '$age < 18)
{
  print "Sorry, you're not old enough!";
}

In a if-statement you can make multiple tests. You have to add elsif.

print "How old are you?";

chomp ($age =<STDIN>);

if '$age < 18)
{
  print "Sorry, you're not old enough!";
}
elsif (&age == 18)
{
  print "Cool, you're just old enough!";
}
else
{
  print "You're old enough!";
}
Besides the if statement, you can also use the terminator ?:.
($a < 10) ? ($b = $a) : ($a = $b);
It can be usefull to only use the else part. You can do this with the unless statement. Perl will execute the unless-part when the result is FALSE.
print "How old are you ?";

comp ($age= <STDIN>);

unless ($age < 18)
{
  print "You're old enough to enter!";
}

While statement

A while statement repeats the same code while a statement is true. You have to make sure that something in the code change the statement at 1 time.

print "How old are you ?";

comp ($age= <STDIN>);

while ($age > 0)
{
  print "at one time, you were $age years old!\n";
  $age--;
}

for statement

A for statement exist of 3 parts= the initialization, the test and a increment/decrement.

@names=("Tom","Bert","Frank","Eli","Brigitte");

for ($i=0; $i <= $#names; $i++)
{
  print "$names[$i]";
}

Foreach statement

A foreach statement shall assign a value from a list to a variable and then do the statements until you reach the end of the list.

@names=("Tom","Bert","Frank","Eli","Brigitte");

foreach $person (@names)
{
  print "$person \n";
}
You don't have to write $person. The following code will do exactly the same.
@names=("Tom","Bert","Frank","Eli","Brigitte");

foreach (@names)
{
  print "$_ \n";
}

 

TOP

Latest script:

 

Books: