Suppose, my global variable and local variables has same name, how can i access the global variable value in subroutine?
$name = "Krishna";
my $name = "Sankalp";
print ("Local name : ", $name, "\n");
# How to print global variable here
print("Global name : ", $name, "\n");
If your global variable is in fact a package variable, you can access it through the package namespace. The default package is
print "Local name : $main::name\n";
Since you're staying in the same namespace, you can omit the
$::name works, too. Both solutions do not work if your outside variable was also defined using
You can define a package variable with
our or via
use names qw($name).
That said, you should never do that. Always use lexical variables, and put them in the smallest scope possible.
use strict and
use warnings will help you, and there is a Perl::Critic rules that complains if you define a variable with the same name as an existing one in a smaller scope.