First, you should use strict
and use warnings
, because that code doesn't compile as it is. What is $self
on line 5? You never define it. Modifying the package code to this:
package Foo;
use strict;
use warnings;
sub new {
my ($class, $args) = @_;
my $hashref = {'a' => 1, 'b' => 2};
bless ($args, $class);
return $args;
}
1;
Now this will compile, but what do you want to do with $hashref
? Are you expecting parameters passed in via $args
or can $hashref
replace $args
? Assuming that $args
really isn't needed, let's use this for Foo
:
package Foo;
use strict;
use warnings;
sub new {
my ($class) = @_;
my $hashref = {'a' => 1, 'b' => 2};
bless ($hashref, $class);
return $hashref;
}
1;
Now, when you call new, you'll be returned a blessed hashref that you can get the keys from:
> 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>