4

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");
1
  • 1
    Don't forget to use strict; use warnings; Commented May 19, 2016 at 6:36

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Does not work. Got error Variable "$name" is not imported at xxx.pl line yy
Forget to mention: not working if "use strict" is used.
@RobinHsu how did you declare that variable? The error indicates you didn't. Also, what Perl version is this?
3

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

2 Comments

You were actually faster :)
Yes, verily I was :). But, you were more precise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.