nithin
nithin

Reputation: 23

How to declare a variable globally so that it's visible for all perl modules?

Hi I have a perl script named main.pl. This perl script is calling three perl modules named sub1.pm, sub2.pm, and sub3.pm. sub.pm is returning three hashes which are being used in sub2.pm and sub3.pm. I am passing the hashes as input parameter to sub2 and sub3. Instead is there any way that I can declare the hashes globally so that it will be visible to these two perl modules?

Upvotes: 2

Views: 1029

Answers (2)

Kenny Grage
Kenny Grage

Reputation: 1124

When you declare non-global variables, it is done by putting "my" in front of it. i.e.:

my $local_variable = 4;

What you are wanting to do is replace the "my" with "our" and make sure it is placed outside of a subroutine. i.e.:

our $global_variable = 4;

If you wish to use it in other modules, you can add it by the following:

use vars qw($global_variable);

Now that I told you how to do it, I am going to tell you not to do it. It is strongly discouraged to use global variables. You should use local variables whenever you can. The reason for this is because if you are ever working on a larger project or a project with multiple coders, then you might find unknown errors as certain variables might not equal what you expect them to because they were changed elsewhere.

Upvotes: 3

Georg Mavridis
Georg Mavridis

Reputation: 2341

Every variable you declare in a module XY with

our $var;
our %hash;

or

use vars qw($var %hash);

is declared global and available as

$XY::var
%XY::hash;

in every other perl-module (if the module has already been used/required).

HTH

Upvotes: 0

Related Questions