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

Hi, The faqs and cookbook all give examples of using scalar instance variables:

  ${self}->{AGE} = 42;

But what is the incantation to make and use a hash instance variable? I know I need to add some $ and {} but where?

Thanks...

Replies are listed 'Best First'.
Re: Howto use hash instance vars?
by Corion (Patriarch) on May 28, 2001 at 13:15 UTC

    You might want to read up on Perl references in perlref and maybe one or two of the Perl object tutorials like perltoot. To the problem at hand, it seems like your object already is an anonymous hash, so you can go accessing its members just like you access your instance :

    sub printkey { my ($self,$key) = @_; print "$key : ", $self->{my_hash}->{$key},"}\n"; }; # Now set up the faked object. The real one would be # with more meat and a constructor I guess. $self = {}; # $self is an anonymous hash (reference) $self->{my_hash} = {}; # so is $self->{my_hash} $self->{my_hash}->{Hello} = "World"; printkey( $self, "Hello" );
Re: Howto use hash instance vars?
by bikeNomad (Priest) on May 30, 2001 at 19:31 UTC
    First, understand that Perl's OO support does not actually include the concept of instance variable. Perl does not provide, for instance, for data inheritance (though you can do it yourself). What we have instead are blessed references to certain primitive things: arrays, hashes, scalars, subroutines.

    There are conventional ways to handle the problem of attaching data to a Perl object (a blessed reference to something). If you have a reference to an array, then an "instance variable" is merely one member of the array. If you have a reference to a hash, then you can make named instance variables using the hash's key/value pairs.

    By the use of use fields, you get a pseudo-hash -- that is, an array with named slots.

    So for a short answer, here are some constructors that show the conventional addition of "instance variables" (I am deliberately not minimizing the code to avoid confusion):

    package HashRefAsObject; sub new1 { # using a hash ref as an object my $class = shift; my $self = { }; # hash ref bless( $self, $class ); $self->{varA} = 123; # set "instvar" $self->{varB} = 456; # another return $self; } package ArrayRefAsObject; sub new2 { # using an array ref as an object my $class = shift; my $self = []; # array ref bless( $self, $class ); $self->[0] = 123; # set "instvar" $self->[1] = 456; # another return $self; } package Foo; # Using pseudo-hashes # from fields manpage: use fields qw(foo bar _Foo_private); sub new { my Foo $self = shift; unless (ref $self) { $self = fields::new($self); $self->{_Foo_private} = "this is Foo's secret"; } $self->{foo} = 10; $self->{bar} = 20; return $self; }