Perl | my keyword

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
  
# Local variable outside of subroutine
my $string = "Geeks for Geeks";
print "$string\n";
  
# Subroutine call
my_func();
print "$string\n";
  
# defining subroutine 
sub my_func
{
    # Local variable inside the subroutine
    my $string = "This is in Function";
    print "$string\n";
    mysub();
}
  
# defining subroutine to show
# the local effect of my keyword
sub mysub 
{
    print "$string\n";
}

chevron_right


Output:

Geeks for Geeks
This is in Function
Geeks for Geeks
Geeks for Geeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
  
# Local variable outside of subroutine
my $string = "Welcome to Geeks";
print "$string\n";
  
# Subroutine call
my_func();
print "$string\n";
  
# defining subroutine 
sub my_func
{
    # Local variable inside the subroutine
    my $string = "Let's GO Geeky!!!";
    print "$string\n";
    mysub();
}
  
# defining subroutine to show
# the local effect of my keyword
sub mysub 
{
    print "$string\n";
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# A perl code to demonstrate dynamic scoping 
$x = 10; 
sub
   return $x
sub
   # Since local is used, x uses   
   # dynamic scoping. 
   local $x = 20; 
  
   return f(); 
  
print g()."\n"

chevron_right




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.