Tuesday, September 8, 2009

After such a long time I am posting few of my learning's on Perl...

Variable Scoping:
In general variables are declared using "my".
my $var= "hello";
Actually its not required. Just use
$var="hello";
Both the statements print "hello".
But the second statement creates global variables throughout the program, which is not recommended.
Using 'my' creates lexically scoped variables. Say bunch of statements surrounded by curly-braces.
The variables declared in between braces are different.

my $var="Hello";
my $num=1;
if($num==1)
{
my $var1="World";
print $var."\n"; #prints Hello
print $var1."\n"; #prints World
}
print $var1; #prints nothing

Output:
Hello
World

Using "my" in combination with a 'use strict;' at the top of the Perl script means that the interpreter will pick up certain common programming errors.
Add 'use strict;' at the top of the script and execute the same script. The final print statement 'print $var1;' would display compile-time error and fail to execute the script.
So add 'use strict;' in the program, which is recommended.

No comments:

Post a Comment