bengmau has asked for the wisdom of the Perl Monks concerning the following question:

How do you properly store a hash to a class variable and call them? here's my code
sub initialize { my $self = shift; #$self->reset; $self->{ SERVERHASHLIST=> '%', SERVERLOCATION=> '%', }; %{$self->{SERVERHASHLIST}}=compileserverhash(); %{$self->{SERVERLOCATION}}=compileserverloc(); #%{$test1->element()} = %aa ; }
My subroutines compileserverhash() create a hash populate it and return a hash in the form
sub compileserverhash { my %hash .... return %hash }

Replies are listed 'Best First'.
Re: class object and hash
by kvale (Monsignor) on Oct 19, 2004 at 19:10 UTC
    Since your hash values are scalars, you want to store a reference to the hash:
    sub compileserverhash { my %hash; # .... return \%hash; }

    -Mark

      I've modified my return code to do the above however when I make the call to:
      my %hashlist = $self->{SERVERLOCATION}
      The contents of %hashlist are a scalar with with value: HASH(ox2023244) am I supposed to assign it in a different way such as: my %hashlist = %{$self->{SERVERLOCATION}}
        arghh.. my goof!!
        %{$self->{SERVERHASHLIST}}=compileserverhash(); %{$self->{SERVERLOCATION}}=compileserverloc();
        Guess I was running low on coffee did the above before posting. as soon as I removed the %{}'s it came in fine with the referencing on the calling subroutine.
        $self->{SERVERHASHLIST}=compileserverhash(); $self->{SERVERLOCATION}=compileserverloc();
        Thanks all
Re: class object and hash
by dave_the_m (Monsignor) on Oct 19, 2004 at 19:54 UTC
    $self->{ SERVERHASHLIST=> '%', SERVERLOCATION=> '%', };
    This doesn't do what you think it might do (and I'm not even sure what you think its doing). Its actually doing a hash element lookup and then throwing the result away; ie it's actually equivalent to
    $self->{ join($; ,'SERVERHASHLIST','%','SERVERLOCATION','%') };

    Dave.

Re: class object and hash
by TedPride (Priest) on Oct 19, 2004 at 23:29 UTC
    use strict; use warnings; my %hash1 = %{create()}; my $ref = create(); my %hash2; give(\%hash2); print $hash1{'a'} . $ref->{'b'} . $hash2{'c'}; sub create { my %hash = ('a' => '1', 'b' => '2'); return \%hash; } sub give { my $ref = shift; %$ref = ('c' => '3', 'd' => '4'); }
    Here's three ways to pass hash data from a sub.