Databases Reference
In-Depth Information
The second line of this script is a use strict; instruction (also known as a pragma ) to
the Perl interpreter to ensure that all variables are explicitly declared with the my key-
word before they are used. This helps avoid problems with mistyped variable names.
You should try to include this line in all your scripts. Otherwise, if you mistype a variable
name in one place, Perl assumes you want to create a new variable and doesn't warn
you about the problem, so the program could fail or produce incorrect output that's
hard to detect.
Any braces (also known as curly brackets) enclosing the variable declaration limit the
scope of the declaration. For example, here the $Time variable is declared only inside
the braces and is not available outside them:
my $Seconds=97;
{
my $Time=$Seconds+1;
print "\nTime: ", $Time;
}
However, the variable $Seconds is available both outside and inside the braces.
A variable defined inside braces will override any existing variable with the same name
outside the braces. For example, we can have two different variables called $counter :
#!/usr/bin/perl
my $counter=10;
print "Before braces: $counter\n";
{
my $counter=33;
print "Within braces: $counter\n";
}
print "After braces: $counter\n";
This produces the results:
Before braces: 10
Within braces: 33
After braces: 10
It's generally not good practice to use different variables with the same names, so avoid
doing so when you can. We've just shown this here to help you understand existing
code and possible causes of problems.
Notice that we've left blank lines between several statements and substrings; Perl ig-
nores such whitespace outside strings. Perl also ignores any lines starting with the hash,
or pound, symbol ( # ); this allows us to write explanatory comments alongside the code.
Judicious use of whitespace and comments can help keep your programs readable and
easy to understand.
 
Search WWH ::




Custom Search