2011-08-04 82 views
-1

我有一个模块foo,它扩展了子模块bar和baz。我想要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?

感谢您的阅读。 :)

+0

什么“散列集”?你所显示的代码中没有任何哈希值。 – tadmc

回答

2

我更喜欢通过方法分享东西。这样一来,没有人知道关于数据结构或变量名,任何东西(虽然你需要知道方法名):

{ 
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'); 
     } 

} 
0

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

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(); 

但是,如果你需要修改实例变量,你必须参考这个实例。我看到一些策略,将工作:

  • 继承Foo,所以散列将在Foo::Bar
  • 通参考实例Foo在构造函数中,并将其存储作为财产Foo::Bar
  • Foo引用作为参数到方法

正确的解决方案取决于您正在尝试做什么以及如何使用它。