Static variables in perl module

I want to set a variable in a module from one calling module and I want to get that value in another calling module.

I did something like 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 getting data like:

package Mod2;
use Test;

print Test::get_data();

      

But I am getting undef when retrieving the value.

What's wrong with my implementation?

+3


source to share


3 answers


I figured out this problem. Setting code

package Mod1;
use Test;

Test::set_data(1);

      



works in a streaming function. I realized that inside the function, the state of the variable changes as expected and I can also access the latest data.

As soon as I exited the threading function, the value of the variable is no longer stored. What I mean by the threaded function is after I have joined all the running threads.

+1


source


Add some debugging (like warn "setting data to $data";

at the end of set_data and warn "getting data: $data";

at the beginning of get_data) and make sure everything happens in the order you think.

Note that the main module code (which both your get_data and set_data calls) is executed when the module is loaded at compile time; if you depend on something else that happens at runtime to get the value it won't work.



If all else fails, highlight as much code as possible and it still fails and show us the case of failure (including any Mod1 and Mod2 loads).

0


source


When I need to do something like this, I usually take the help of Storable . You can use this method.

See this answer ( fooobar.com/questions/2037066 / ... ) for an example.

0


source







All Articles