Hari Krishna
Hari Krishna

Reputation: 3568

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");

Upvotes: 4

Views: 10894

Answers (2)

Arunesh Singh
Arunesh Singh

Reputation: 3535

You need to declare a package variable instead of lexical variable using our. Inside a subroutine you need to fully qualify it to address it. If you need to share variables across packages you should use our.

my declares the variable in lexical scope. So, the variable dies once it is out of scope. These variables are also private and can't be acessed by other packages.

#!/usr/bin/perl
use strict;
use warnings;

our $name = "Krishna";

sub printName {
    my $name = "Sankalp";
    print ( "Local \$name: ", $name,"\n" );
    print ( "Global \$name: ", $main::name, "\n" ); # or $::name inside the same package
}

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

Upvotes: 3

simbabque
simbabque

Reputation: 54381

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.

Upvotes: 8

Related Questions