2012-03-13 80 views
7

是最好还是最差的方法之一?我应该如何将对象传递给子例程?

利用范围:

my $cache = CHI->new(driver => 'File', expires_in => 3600); 

sub one { 
    if (my $data = $cache->get('key_one')) { 
    # ... 
} 

sub two { 
    if (my $data = $cache->get('key_two')) { 
    # ... 
} 

传递对象作为参数:

my $cache = CHI->new(driver => 'File', expires_in => 3600); 

sub one { 
    my ($cache) = @_; 
    if (my $data = $cache->get('key_one')) { 
    # ... 
} 

sub two { 
    my ($argument1, $cache) = @_; 
    if (my $data = $cache->get('key_two')) { 
    # ... 
} 

或在子程序创建一个新的实例:

sub one { 
    my $cache = CHI->new(driver => 'File', expires_in => 3600); 
    if (my $data = $cache->get('key_one')) { 
    # ... 
} 

sub two { 
    my $cache = CHI->new(driver => 'File', expires_in => 3600); 
    if (my $data = $cache->get('key_two')) { 
    # ... 
} 

回答

9

首先选择使用一个全局变量,不那么热。第三种选择是很多额外的开销。不是那么好,所以我猜中间选择在你的问题的背景下更可取。一个更广泛的问题是为什么子例程需要知道缓存呢?看起来他们只是在担心数据。我会考虑获取数据并将其传递给子例程,在那里他们不必担心它是否被缓存或刚刚创建。

6

除非你想改变原有的数据,它的安全通过引用传递的参数,使用方法2:

my $cache = CHI->new(driver => 'File', expires_in => 3600); 

one (\$cache); 

sub one { 
    my ($cache) = @_; 
    if (any {!defined @_} $cache { //can expand on this 
     croak "missing parameters"; 
    if (my $data = $cache->get('key_one')) { 
    # ... 
}