AFAIK不可能有两个变量总是共享相同的值。以下是一些可以帮助您的想法:
包变量:
{
package test1;
our $var;
sub step1 {$var = "Hello"}
}
{
package test2;
our $var;
sub step1 {$var .= " World!\n"}
}
test1::step1();
$test2::var = $test1::var;
test2::step1();
print $test2::var;
评语:丑
参考:
{
package test1;
our $varref;
sub init {
my ($ref) = @_;
$varref = $ref;
}
sub step1 {$$varref = "Hello"}
}
{
package test2;
our $varref;
sub init {
my ($ref) = @_;
$varref = $ref;
}
sub step1 {$$varref .= " World!\n"}
}
my $var = "";
test1::init(\$var);
test2::init(\$var);
test1::step1();
test2::step1();
print $var;
评论:更好,但需要更多代码。
一个额外的共享模块:
{
package test::shared;
our $var;
}
{
package test1;
sub step1 {$test::shared::var = "Hello"}
}
{
package test2;
sub step1 {$test::shared::var .= " World!\n"}
}
test1::step1();
test2::step2();
print $test::shared::var;
评论:有一些优点。
显式状态
{
package test1;
sub step1 {
my $state = @_;
$state->{var} = "Hello";
return $state; # superfluous, but helps understanding
}
}
{
package test2;
sub step1 {
my $state = @_;
$state->{var} .= " World!\n";
return $state; # superfluous, but helps understanding
}
}
my $state = {};
$state = test1::step1($state); # equiv: test1::step1($state), because of references
$state = test2::step1($state);
print $state->{var};
评论:这几乎是面向对象的编程。我更喜欢这种模式,因为它明确说明了何时给出共享。在多线程和重入方面,显式状态可以轻松扩展您的应用程序。
成本:明确性。冗长的语法。
好处:可重入,通过明确性清晰思路。