Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 239
Feynman Avatar asked Nov 28 '22 11:11

Feynman


2 Answers

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}} { ... }
...
like image 83
mob Avatar answered Dec 01 '22 02:12

mob


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.

like image 38
hobbs Avatar answered Dec 01 '22 01:12

hobbs