在多个子模块之间共享变量



我有一个扩展子模块bar和baz的模块foo。我希望bar和baz能修改foo中的哈希值

现在我有这样的内容:

my $foo = new foo;
my $bar = new foo::bar( $foo );
$bar->doStuff();
$bar->printSelf();
my $baz = new foo::bar( $foo );
$baz->doOtherStuff();
$baz->printSelf();

在其中一个子模块中,构造函数如下:

sub new {
  my $class = shift;
  my $self  = shift;
  --stuff--
  bless $self, $class;
  return $self;
}

请不要笑得太厉害。有没有一种方法,我可以做到这一点,而不传入$foo?

感谢阅读。:)

我更喜欢通过方法来分享东西。这样,就不需要知道任何关于数据结构或变量名的信息(尽管您确实需要知道方法名):

 {
 package SomeParent;
 my %hash1 = ();
 my %hash2 = ();
 sub get_hash1 { %hash1 }
 sub get_hash2 { %hash2 }
 sub set_hash1_value { ... }
 sub set_hash1_value { ... }
 }

由于SomeParent提供了获取私有数据结构的接口,这就是您在SomeChild中使用的:

 {
 package SomeChild;
 use parent 'SomeParent';
 sub some_method {
      my $self = shift;
      my $hash = $self->get_hash1;
      ...;
      }
 sub some_other_method {
      my $self = shift;
      $self->set_hash2_value( 'foo', 'bar' );
      }
 }

你的问题不是很清楚,也没有任何哈希代码。但是如果需要修改模块变量,可以使用完全限定名:

package Foo;        # don't use lowercase named, they are reserved for pragmas
our %hash1 = ();
our %hash2 = ();

package Foo::Bar;
use Data::Dump qw(dd);
sub do_stuff {
    $Foo::hash1{new_item} = 'thing';
}
sub do_other_stuff {
    dd %Foo::hash1;
}

package main;
Foo::Bar->do_stuff();
Foo::Bar->do_other_stuff();

但是如果你需要修改instance变量,你需要有对这个实例的引用。我看到了一些可行的策略:

  • 继承自Foo,因此哈希值将在Foo::Bar
  • 的实例中
  • 在构造函数中传递Foo的引用,并将其作为属性存储在Foo::Bar
  • Foo引用作为参数传递给方法

正确的解决方案取决于你想做什么以及你将如何使用它。

最新更新