# Temporary Values via local() in Perl

PERLServer Side ProgrammingProgramming Scripts

The local is mostly used when the current value of a variable must be visible to called subroutines in Perl. A Perl local just gives temporary values to global (meaning package) variables. This is known as dynamic scoping. Lexical scoping is done with my, which works more like C's auto declarations

If more than one variable or expression is given to local, they must be placed in parentheses. This operator works by saving the current values of those variables in its argument list on a hidden stack and restoring them upon exiting the block, subroutine, or eval.

## Example

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

Live Demo

#!/usr/bin/perl
# Global variable
$string = "Hello, World!"; sub PrintHello { # Private variable for PrintHello function local$string;
$string = "Hello, Perl!"; PrintMe(); print "Inside the function PrintHello$string\n";
}
sub PrintMe {
print "Inside the function PrintMe $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 PrintMe Hello, Perl!
Inside the function PrintHello Hello, Perl!
Outside the function Hello, World!
Published on 29-Nov-2019 07:03:34