Using Blocks
Learn how to manage hundreds of line by using blocks.
The simple scripts we wrote made use of global variables for the sake of simplicity. However, when a script is hundreds of line long using global variables will be a problem as you may want to use the same variable name more than once and define where that variable name is valid. For example you may want to use a variable name “count” in a while loop but also use “count” as the name for another variable that will be in another part of the script. Perl allows you to do that by using the “my” or “our” prefix.
"My" will restrict the use of the variable to the block it is in.
"Our" will define a variable for the whole script. You will not be able to reuse that name even in a block.
Example :
#!/usr/bin/Perl -w
# author:
#modified by:
# date:
#Purpose: Hello World
My $name = “marc”;
Our $age = “35”;
print “$name” , “n”;
print “$age” , “n”;
{
My $name = “eric”
print “$name” , “n”;
print “$age” , “n”;
}
#END
The two column {} define a block. Inside that block you can refine variables that will only exist inside that block. The script below would echoMarc 35 Eric 35Because $name is used with the prefix “my” it can be reused inside a block with the “my” prefix. But $age cannot, because it uses the prefix “our”. If you tried to redefine the variable in the block like in the following script you would get a compilation error:
#!/usr/bin/Perl -w
# author:
#modified by:
# date:
#Purpose: Hello World
My $name = “marc”;
Our $age = “35”;
print “$name” , “n”;
print “$age” , “n”;
{
My $name = “eric”
My $age = “54”
print “$name” , “n”;
print “$age” , “n”;
}
#END