sid*_*com 7 perl arguments object subroutine
这些中最好的还是最差的方法之一?
利用范围:
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' ) ) {
# ...
}
Run Code Online (Sandbox Code Playgroud)
传递对象作为参数:
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' ) ) {
# ...
}
Run Code Online (Sandbox Code Playgroud)
或在子程序中创建一个新实例:
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' ) ) {
# ...
}
Run Code Online (Sandbox Code Playgroud)
第一种选择使用全局变量,而不是那么热.第三种选择是额外的开销.也不是那么好,所以我想中间选择在你的问题的背景下更可取.更广泛的问题是为什么子程序需要知道缓存?看起来他们只担心数据.我会考虑获取数据并将其传递给子例程,如果它被缓存或刚刚创建,他们不必担心.
除非您想要更改原始数据,否则使用方法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' ) ) {
# ...
}
Run Code Online (Sandbox Code Playgroud)