.:: Welcome To My Personal Blog ::.

Saturday, March 5, 2011

Beginner's Guide To Travel With Perl - Part 5

Scope - Something Important

It’s time to say something important now. We can declare any variable in two ways – First is writing variable name with $ sign and assigning a value to it. The second is to write variable name $ sign and adding “my” before it when the variable is used first time.



Example:
$number = 5;
my $number = 5;

Both of them work similarly but there is a difference. Declaring a variable without “my” before it, will create global variables throughout your program, which is bad programming practice. “my” creates lexically scoped variables instead. The variables are scoped to the block (i.e. a bunch of statements surrounded by curly-braces) in which they are defined.

Example:
my $x = "abc";
my $some_condition = 1;
if ($some_condition) {
my $y = "def";
print $x; # prints "abc"
print $y; # prints "def"
}
print $x; # prints "abc"
print $y; # prints nothing; $y has fallen out of scope

Using “my” in combination with a “use strict” at the top of the Perl scripts means that, the interpreter will pick up certain common programming errors. For instance, in the example above, the final print $y would cause a compile-time error and prevent you from running the program.

Example:
use strict;
my $x = "abc";
my $some_condition = 1;
if ($some_condition) {
my $y = "def";
print $x; # prints "abc"
print $y; # prints "def"
}
print $x; # prints "abc"
print $y; # prints nothing; $y has fallen out of scope

Using strict is highly recommended.


Help Links:

http://www.perl.com/pub/2000/10/begperl1.html
http://perldoc.perl.org/perlintro.html

http://www.perl.org/learn.html
http://learn.perl.org/books.html
http://learn.perl.org/tutorials/
http://www.perl.com/pub/2008/04/23/a-beginners-introduction-to-perl-510.html
http://docstore.mik.ua/orelly/perl2/prog/ch01_05.htm
http://www.tizag.com/perlT/perluserinput.php
http://www.tizag.com/perlT/perlchomp.php

http://perldoc.perl.org/functions/use.html
http://www.well.ox.ac.uk/~johnb/comp/perl/intro.html

http://www.sthomas.net/roberts-perl-tutorial.htm/ch22/use_strict_
http://docstore.mik.ua/orelly/perl/prog3/ch31_19.htm
http://debugger.perl.org/580/perldebtut.html
http://perldoc.perl.org/strict.html


. . . . . To be continued . . . . .

No comments:

Post a Comment

Popular Posts