如何在Perl中使类的成员成为哈希?

Fey*_*man 4 perl hash class object

我正在尝试用perl编写一个包.我需要其中一个成员成为哈希.但是,当我引用并运行程序时,我无法使用通常的语法.如果我有:

sub new
{
my $class = shift;
my $self = {
    textfile => shift,
    placeholders => ()
};
bless $self, $class;
return $self;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让"占位符"成为我可以通过$ self - > {placeholders}访问的哈希?

谢谢

mob*_*mob 10

是的,但您必须将其作为哈希引用.

$self = {
   textfile => shift,
   placeholders => { }         #  { }, not ( )
};
...


$self->{placeholders}->{$key} = $value;
delete $self->{placeholders}->{$key};
@keys = keys %{$self->{placeholders}};
foreach my ($k,$v) each %{$self->{placeholders}} { ... }
...
Run Code Online (Sandbox Code Playgroud)


hob*_*bbs 6

聚合的所有成员(数组,散列和作为数组的对象都是散列)都是标量.这意味着散列中的项永远不是另一个数组或散列,但它可以是数组或散列引用.

你想做(第一次近似):

sub new {
  my $class = shift;
  my ($textfile) = @_;
  my $self = {
    textfile => $textfile,
    placeholder => {},
  };
  return bless $self, $class;
}
Run Code Online (Sandbox Code Playgroud)

然后,当你使用它(假设你也有placeholder访问),您可以使用$obj->placeholder->{key},%{ $obj->placeholder }等等.