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


i still learning object oriented perl , struggling bit on how access classes.

i've created class 1 of attributes hash. when want print directly value of given key in hash, output blank. if assign new variable value of hash, can print variable.

toy example code:

 sub new {       my($clas) = @_;     my($self) = {};       bless($self,$clas);     $self->{age_record} = {};     return($self);   }  

imaginary code fills hash

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

let's use data::dumper see what's in hash.

print dumper $class->{age_record}; $var1 = {          'rigobert' => 17,          'helene' => 42        }; 

i nothing if print directly.

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

but if asign first new variable, works.

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

i

age : 17 

what doing wrong when referencing hash attribute?

as far can see there nothing wrong, , reason can think of output not appearing is buffered. should try adding

stdout->autoflush; 

near top of program.

however, shouldn't accessing internal data structures calling code. fill_hash should better_named method , need write accessor method age_record element. this

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

and can call as

printf "age : %d\n", $class->pupil_age('rigobert'); 

(the printf style choice — there's no other need use above simple print)


Comments