Perl | my keyword
Last Updated :
07 May, 2019
my keyword in Perl declares the listed variable to be local to the enclosing block in which it is defined. The purpose of my is to define static scoping. This can be used to use the same variable name multiple times but with different values.
Note: To specify more than one variable under my keyword, parentheses are used.
Syntax: my variable
Parameter:
variable: to be defined as local
Returns:
does not return any value.
Example 1:
my $string = "Geeks for Geeks" ;
print "$string\n" ;
my_func();
print "$string\n" ;
sub my_func
{
my $string = "This is in Function" ;
print "$string\n" ;
mysub();
}
sub mysub
{
print "$string\n" ;
}
|
Output:
Geeks for Geeks
This is in Function
Geeks for Geeks
Geeks for Geeks
Example 2:
my $string = "Welcome to Geeks" ;
print "$string\n" ;
my_func();
print "$string\n" ;
sub my_func
{
my $string = "Let's GO Geeky!!!" ;
print "$string\n" ;
mysub();
}
sub mysub
{
print "$string\n" ;
}
|
Output:
Welcome to Geeks
Let's GO Geeky!!!
Welcome to Geeks
Welcome to Geeks
How to define dynamic scoping?
The opposite of “my” is “local”. The local keyword defines dynamic scoping.
$x = 10;
sub f
{
return $x ;
}
sub g
{
local $x = 20;
return f();
}
print g(). "\n" ;
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...