I have two modules: test1 and test2 and I need to run their subroutines in sequence. They need to modify the same variable $var and the outer script needs to print the final result. This unfortunately doesn’t work, and seems to be very similar to this S.O. Question.
#test1.pm
use strict;
package test1;
my $var;
sub step1 {
$var = "Hello";
}
1;
#test2.pm
use strict;
package test2;
my $var;
sub step1 {
$var = $var." World!\n";
}
1;
#execTests.pl
use strict;
require test1;
require test2;
&test1::step1;
&test2::step1;
print $test2::var;
How do I make $var be included in the same scope of both required packages?
AFAIK it is not possible to have two variables always share the same value. Here are some Ideas that could help you:
Package variables:
Comment: Ugly
References:
Comment: Better, but requires more code.
An extra shared module:
Comment: Has some advantages.
Explicit state
Comment: this is almost object oriented programming. I would prefer this pattern, as it is explicit about what shared is given when. Explicit state makes it easy to scale your application, in terms of multithreading and reentrancy.
Cost: expliciteness. verbose syntax.
Benefit: Reentrancy, clear train of thought via expliciteness.