Private Variables in a Subroutine in Perl

PERLServer Side ProgrammingProgramming Scripts

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 cannot be used or accessed. This region is called its scope. 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
}

Example

Let's check the following example to distinguish between global and private variables −

 Live Demo

#!/usr/bin/perl
# Global variable
$string = "Hello, World!";
# Function definition
sub PrintHello {
   # Private variable for PrintHello function
   my $string;
   $string = "Hello, Perl!";
   print "Inside the function $string\n";
}
# Function call
PrintHello();
print "Outside the function $string\n";

Output

When the above program is executed, it produces the following result −

Inside the function Hello, Perl!
Outside the function Hello, World!
raja
Published on 29-Nov-2019 11:31:28
Advertisements