そのコードはそのままではコンパイルされないため、最初に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>