我对将某些参数传递给构造函数类型的不同方法有点模糊。我只想传递一个哈希引用\%hash
或一个列表foo => 1, bar => 1
,但不能同时传递两者,croak
如果还有其他传递,即( single elements, array reference )
。
例如,我通过我的参考或列表..(This works for the way I do this)
my $obj = foo->new;
my $data = $obj->dump( \%hash );
my $data = $obj->dump( foo => 1, bar => 1 );
或者
my $obj = foo->dump( \%hash );
my $obj = foo->dump( foo => 1, bar => 1 );
封装模块:
package foo;
use strict;
use Carp;
use Scalar::Util qw/reftype/;
sub new { return bless {}, shift }
sub dump {
my $class = shift;
my $self = shift;
unless ( reftype( $self ) eq reftype {} ) {
croak("Constructor method not a hash type!");
}
}
1;
我也考虑过在? :
这里使用条件运算符,但我无法让它正确出错。
my $self = reftype($_[0]) eq reftype {} ? shift : {@_};
有更好的首选方法吗?