我有一个带有getter和setter方法的类。我正在创建这个类的对象的哈希。
my %hash;
$hash{'foo'} = Myclass->new();
$hash{'bar'} = Myclass->new();
...
使用创建的对象,我试图将数据设置为包的特定属性。它是成功的,并没有显示任何问题。但是,如果我尝试检索数据,则返回设置的最后一个值。
代码:
#!/usr/bin/perl
package Metadata;
my $myname = "";
sub new {
my $type = shift;
my $self = {};
bless $self, $type;
return $self;
}
sub setMyname {
my ($self, $tempName) = @_;
$myname = $tempName;
}
sub getMyname {
return $myname;
}
package main;
use YAML::XS 'LoadFile';
use Data::Dumper;
my %objHash = ();
my @list;
my $myname;
my $i = 0;
my @conf = LoadFile('input.yml');
my $config = \@conf;
foreach ( @conf ) {
$list[$i] = $config->[$i]->{mykey};
$objHash{$list[$i]} = Metadata->new();
$myname = $config->[$i]->{myname};
$objHash{$list[$i]}->setMyname($myname);
my $host = $objHash{$list[$i]}->getMyname();
$i++;
}
my $host = $objHash{$list[0]}->getMyname();
print $host;
print "\n";
my $host = $objHash{$list[1]}->getMyname();
print $host;
print "\n";
my $host = $objHash{$list[2]}->getMyname();
print $host;
print "\n";
YAML:
---
mykey: 1
myname: John
---
mykey: 2
myname: Doe
----
mykey: 3
myname: Chris
...
预期输出
John
Doe
Chris
Chris
Chris
Chris
我错过了什么吗?
答案 0 :(得分:3)
您在$myname
而不是在对象中存储每个对象的名称!
package Metadata;
use strict;
use warnings qw( all );
sub new {
my ($class) = @_;
my $self = bless({}, $class);
$self->{name} = undef;
return $self;
}
sub set_name {
my ($self, $name) = @_;
$self->{name} = $name;
}
sub get_name {
my ($self) = @_;
return $self->{name};
}
1;