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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With