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

How would i properly access "hash reference member"? See "PrintHash" for what I'm trying to do. Thanks.

X.pm:
package X; sub new { my ($class) = @_; my %ht = (); %ht= ("x" => "y"); my $self = { HREF => \%ht, }; bless $self, $class; return $self; } sub PrintHash { my($self) = @_; # this doesn't work ("scalar found where operator expected"): # while( my ($k, $v) = each (%$self->{HREF}) ) # . . . } 1;

main.pl:
use X; my $x = new X(); $x->PrintHash();

Replies are listed 'Best First'.
Re: hash ref as member of class
by JavaFan (Canon) on Aug 11, 2009 at 16:22 UTC
    Almost there. each %{$self->{HREF}} should do. In general, if you have an expression ($self->{HREF} is an expression) that yields a hashref, putting %{ } around that expression gives you the hash.

      Just as an aside for the OP why your initial try was wrong: your %$self->{HREF} parses as (%{$self})->{'HREF'} because %$self is a complete term to which the -> deref operator is (unsuccessfully) applied. Using the curlies works kind of like specialized parens letting perl know that what you want to dereference is the hashref the expression $self->{HREF} contains.

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.

        thanks that makes sense. I initially tried %($self->{HREF}) w/ parens instead of curly braces. perl is confusing like that - you initalize a hash with parens, access and derefence with curly braces, etc.
      gracias! that did it