代码中有2个包。
套餐1:
package Foo;
sub new {
my ($class, $args) = @_;
my $hashref = {'a' => 1, 'b' => 2};
bless ($self, $class);
return $self;
}套餐2:
package Fuz;
use Foo;
.
.
.
.
my $obj = Foo->new($args);如何获取对象中受祝福的hashref的密钥?
我知道perl中的Acme::Damn和Data::Structure::Util模块可以解除对象的限制。有没有其他方法可以做到这一点?
发布于 2013-12-30 20:10:20
支持散列引用并不会改变它仍然是散列引用。因此,您可以像往常一样取消引用它:
my @keys = keys %$obj;发布于 2013-12-30 20:14:26
首先,您应该使用use strict和use warnings,因为这些代码不会按原样编译。第5行上的$self是什么?你从来没有定义过它。将包代码修改为:
package Foo;
use strict;
use warnings;
sub new {
my ($class, $args) = @_;
my $hashref = {'a' => 1, 'b' => 2};
bless ($args, $class);
return $args;
}
1;现在可以编译了,但是你想用$hashref做什么呢?您是否期望通过$args传入参数,或者$hashref可以取代$args吗?假设确实不需要$args,让我们对Foo使用它
package Foo;
use strict;
use warnings;
sub new {
my ($class) = @_;
my $hashref = {'a' => 1, 'b' => 2};
bless ($hashref, $class);
return $hashref;
}
1;现在,当您调用new时,将返回一个受祝福的hashref,您可以从中获取密钥:
> perl -d -Ilib -e '1'
Loading DB routines from perl5db.pl version 1.33
Editor support available.
Enter h or `h h' for help, or `perldoc perldebug' for more help.
main::(-e:1): 1
DB<1> use Foo
DB<2> $obj = Foo->new()
DB<3> x $obj
0 Foo=HASH(0x2a16374)
'a' => 1
'b' => 2
DB<4> x keys(%{$obj})
0 'a'
1 'b'
DB<5>发布于 2013-12-30 20:12:26
您仍然可以在$obj上使用密钥
my $obj = Foo->new($args);
my @k = keys %$obj;https://stackoverflow.com/questions/20839154
复制相似问题