Hari Krishna Hari Krishna - 6 months ago 29
Perl Question

How to access global variable in subroutine

Suppose, my global variable and local variables has same name, how can i access the global variable value in subroutine?

#! /usr/bin/perl

$name = "Krishna";

sub printName{
my $name = "Sankalp";

print ("Local name : ", $name, "\n");
# How to print global variable here
}

&printName;
print("Global name : ", $name, "\n");

Answer

If your global variable is in fact a package variable, you can access it through the package namespace. The default package is main.

print "Local name : $main::name\n";

Since you're staying in the same namespace, you can omit the main, so $::name works, too. Both solutions do not work if your outside variable was also defined using my.

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.

Comments