| Lesson 7 - Flow Control |
| Flow
Control Flow Control in
any programming language is very important. Establishing flow control
is the only way you can develop a
The most basic test
you can use is the `if` statement. The commands in an `if` block will
execute only if the test you are $a
= 0; if
($a == $b) { In this case the
if statement can not evaluate to true becuase `$a` (which is `0`) can
never equal `$b` (`1`). If you made A more advanced use of `if` is `elsif` and `else`. An example is below. $a = "Test String"; if
($a eq "Not a test") { In this example
`$a` will go through each test until it gets to one that is true. If
it can't find any true statements the Note that we used
`eq` commands instead of `==` commands in the tests. This is becuase
we are testing strings and not
Tests $a
= 1; In this example
your program output will be `$a is zero.` simply because you used `=`
instead of `==` in your test. Using a Test Meaning
The while statement will do something while a statement is true: $a = 0; while
($a != 10) { This look will increment `$a` while `$a` is not equal to `10`. A very useful application of the while statement is with File I/O (see File I/O topic.) You can use statements like this: while
(<FILEHANDLE>) { This block of commands
will execute printing out `$_` (which contains a line from the file)
while there are more lines in
The `unless` command is just like the `if` command inverted. You can use statements like: unless
($a eq "Test") { This will run the command inside the `unless` block unless `$a` is equal to `Test`.
Foreach loops will run the loop for each value cited. An example follows: foreach
$value (@in) { This example will
print out each value in the array `@in`. You can also drop the $value
part of this statement and the values foreach
(@in) { This is shorter
but you can never be gaurenteed that `$_` will not change on you somewhere
when you don't expect it to change.
Subroutines in perl are defined with the keyword `sub`. You can create a sub using: sub
mysub { By executing `&mysub();`
the sub will be executed and after execution control returned to the
next command after you called Subs can also returns
values, in which case they become a function. To use this feature of
perl call your sub like An example: $ret
= &returnsub(); sub
returnsub The above example will print out the contents of `$ret`, which are `My String` after it gets set from the results `returnsub`. Data can also be
passed to a sub in perl. You can use this by calling the sub like `&mysub($passthis);`.
This will pass the An full example of evertyhing we have learned about the use of subroutines: $printthis
= "Print This String\n"; sub
returnsub This example will print "Print This String\n"; |