but I don't know how to create a hash as a data member
$self->{myhash} = {};
But maybe you don't even need an extra hash, as Perl objects often are hashes (like the $self here)... so unless you have other object attributes that might get in the way, you could maybe store the key-value pairs in the object directly.
(Update) With extra hash:
package MyClass;
sub new {
my $class = shift;
my $self = { @_ };
$self->{myhash} = {};
return bless $self, $class;
}
sub set_attr {
my $self = shift;
my ($key, $val) = @_;
$self->{myhash}{$key} = $val;
}
sub get_attr {
my $self = shift;
my $key = shift;
return $self->{myhash}{$key};
}
package main;
my $obj = MyClass->new();
$obj->set_attr( foo => "bar" );
print $obj->get_attr("foo"), "\n";
Without:
package MyClass;
sub new {
my $class = shift;
my $self = { @_ };
return bless $self, $class;
}
sub set_attr {
my $self = shift;
my ($key, $val) = @_;
$self->{$key} = $val;
}
sub get_attr {
my $self = shift;
my $key = shift;
return $self->{$key};
}
...
|