How do I make a member of a class a hash in Perl?
I am trying to write a package in perl. I need one of the members to be a hash. However, when I reference and run the program, I cannot 开发者_开发技巧get it to work with the usual syntax. If I have:
sub new
{
my $class = shift;
my $self = {
textfile => shift,
placeholders => ()
};
bless $self, $class;
return $self;
}
Is there any way of making "placeholders" a hash I can access via $self->{placeholders} ?
Thanks
Yes, but you have to make it a hash reference.
$self = {
textfile => shift,
placeholders => { } # { }, not ( )
};
...
$self->{placeholders}->{$key} = $value;
delete $self->{placeholders}->{$key};
@keys = keys %{$self->{placeholders}};
foreach my ($k,$v) each %{$self->{placeholders}} { ... }
...
All members of aggregates (arrays, hashes, and objects that are arrays are hashes) are scalars. That means that an item in a hash is never another array or hash, but it can be an array or hash reference.
You want to do (to a first approximation):
sub new {
my $class = shift;
my ($textfile) = @_;
my $self = {
textfile => $textfile,
placeholder => {},
};
return bless $self, $class;
}
And then when you use it (assuming that you also have a placeholder
accessor), you can use $obj->placeholder->{key}
, %{ $obj->placeholder }
, etc.
()
constructs an empty list. This is fine when you are assigning to a %hash
but otherwise, Perl just treats it as an empty list which is merged into the surrounding list. Just as you did when you assigned to $self
, you need to use the curly braces { }
to construct an anonymous hash reference.
You want a hash reference. Use curly braces instead of parentheses:
sub new {
my $class = shift;
bless { textfile => shift, placeholders => {} }, $class;
}
精彩评论