首先,您应该use strict
and 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>