2011-08-04 48 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引用作爲參數到方法

正確的解決方案取決於您正在嘗試做什麼以及如何使用它。