Static variables in perl module

1.2k Views Asked by At

I want to set a variable in a module from one calling module and want to retrieve that value inanother calling module.

I have done something line this:

package Test;

our $data = undef;

sub set_data
{
    $data = shift @_;
}

sub get_data
{
    return $data
}

I am setting the data as :

package Mod1;
use Test;

Test::set_data(1);

I am retrieving the data as:

package Mod2;
use Test;

print Test::get_data();

But I am getting undef while retrieving the value.

What is wrong in my implementation?

3

There are 3 best solutions below

2
On

Add some debugging (e.g. warn "setting data to $data"; at the end of set_data and warn "getting data: $data"; at the beginning of get_data) and verify things are happening in the order you think they are.

Note that the main code of a module (which both your get_data and set_data calls are) runs when the module is loaded at compile time; if you are depending on something else that happens at run time to get the value, that won't work.

If all else fails, strip out as much of your code as you can and still have it fail and show us the compete failing case (including whatever loads Mod1 and Mod2).

1
On

I have figured out the problem. The setter code

package Mod1;
use Test;

Test::set_data(1);

is running in a threaded function. I figured out that inside the function the state of the variable is getting changed as expected and I can also access the latest data.

Once I am out of the threaded function the value of the variable no more persists. What I mean by out of the threaded function is after I joined all the running threads.

1
On

When I have to do something like that I usually take help of Storable. You can use that method.

See this answer (https://stackoverflow.com/a/17082242/257635) for an example.