next up previous contents
Next: If/Unless statement Up: Perl Statements Previous: Statement Blocks

Statement Blocks and Local Variables

Normally, it's a good idea to place all of your variable initialization at the top of a program or function. However, if you are maintaining some existing code, you may want to use a statement block and local variables to minimize the impact of your changes on the rest of the code-especially if you have just been handed responsibility for a program that someone else has written.

You can use the my() function (See next Chapter for complete discussion on functions) to create variables whose scope is limited to the statement block. This technique is very useful for temporary variables that won't be needed elsewhere in your program. For example, you might have a complex statement that you'd like to break into smaller ones so that it's more understandable. Or you might want to insert some print statements to help debug a piece of code and need some temporary variables to accommodate the print statement.

For example (print.pl):

$firstVar = 10;

{

   my($firstVar) = "A";

   print $firstVar x 5 . "\n";



}

print("firstVar = $firstVar\n");

This program displays:

AAAAA

firstVar = 10

We now concetrate on a brief overview of Perl's conditional statements



dave@cs.cf.ac.uk