Bala Krishnan
Bala Krishnan

Reputation: 374

Perl - data retrieval with hash of objects

I have a class with getter and setter methods. I am creating a hash of objects of this class.

my %hash;

$hash{'foo'} = Myclass->new();
$hash{'bar'} = Myclass->new();
...

With a created object I am trying to set the data to a particular attribute of the package. It is successful and doesn't show any issues. But if I try to retrieve the data, the last value that is set is returned.

Code:

#!/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
...

Expected output

John
Doe
Chris

Actual output

Chris
Chris
Chris

Am I missing anything?

Upvotes: 2

Views: 88

Answers (1)

ikegami
ikegami

Reputation: 386561

You're storing the names of every object in $myname instead of in the object!

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;

Upvotes: 3

Related Questions