Thursday, April 3, 2014

perl private variables

Private Variables in a Subroutine:

By default, all variables in Perl are global variables which means they can be accessed from anywhere in the program. But you can create private variables called lexical variables at any time with the my operator.
The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable can not be used or accessed. This region is called its scope. A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval statements.
Following is an example showing you how to define a single or multiple private variables using my operator:
sub somefunc {
   my $variable; # $variable is invisible outside somefunc()
   my ($another, @an_array, %a_hash); # declaring many variables at once
}

No comments:

Post a Comment