pedrosaurio
pedrosaurio

Reputation: 4926

How can I access an scalar iside a hash atribute of a class in perl?

I am still learning some object oriented perl and I am struggling a bit on how to access my classes.

I've successfully created a class which one of its attributes is a hash. When I want print directly the value of a given key in this hash, the output is always blank. If I assign a new variable to the value of the hash, then I can print this variable.

Toy example code:

 sub new {  
    my($clas) = @_;
    my($self) = {}; 

    bless($self,$clas);
    $self->{age_record} = {};
    return($self);  
} 

Imaginary code that fills up my hash

my $class->new("class");
fill_hash($class);

Let's use Data::Dumper to see what's in the hash.

print Dumper $class->{age_record};
$VAR1 = {
         'Rigobert' => 17,
         'Helene' => 42
       };

I get nothing if I print directly.

 print $class->{age_record}{'Rigobert'};

But if I asign it first to a new variable, it works.

my $age = $class->{age_record}{'Rigobert'};
print "Age is : $age\n";

I get

Age is : 17

What am I doing wrong when referencing the hash attribute?

Upvotes: 2

Views: 55

Answers (2)

Dave Cross
Dave Cross

Reputation: 69274

I'm puzzled by the line

my $class->new("class");

It should be something like:

my $class = Class->new();

(Assuming that your class's name is "Class" - it's pretty confusing having a class called "Class". I'm assuming that you have class modelling an academic class!)

Then you'd have a method to add a pupil.

sub add_pupil {
  my ($self, $name, $age) = @_;

  $self->{age_record}{$name} = $age;
}

And another method to get a pupil.

sub get_pupil {
  my ($self, $name) = @_;

  return $self->{age_record}{$name};
}

You'd then use it like this.

my $class = Class->new();
$class->add_pupil('Rigobert', 17);
$class->add_pupil('Helene', 42);

print $class->get_pupil('Rigobert'); # prints 17

I think you're confused because you haven't really thought about how you are modelling your data inside the class. And I can't be much more help as I don't know what the other attributes are or what your fill_hash() subroutine looks like.

Upvotes: 0

Borodin
Borodin

Reputation: 126722

As far as I can see there is nothing wrong, and the only reason I can think of for your output not appearing is that it is buffered. You should try adding

STDOUT->autoflush;

near the top of your program.

However, you shouldn't be accessing internal data structures from the calling code. fill_hash should be a better_named method and you need to write an accessor method to get to the age_record element. Something like this

sub pupil_age {
    my $self = shift;
    my ($name) = @_;
    $self->{age_record}{$name};
}

and then you can call it as

printf "Age is : %d\n", $class->pupil_age('Rigobert');

(The printf is just a style choice — there's no other need to use it above a simple print)

Upvotes: 2

Related Questions