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

Hi, a novice question about objects:

I use the standard $self = {} for my objects...

I usually create get/set routines, which help with readability...but I haven't figured out the best way to allow the user (me) to enumerate the hash w/o knowing the structure...
my %all = $obj->GetALL(); foreach (keys %all) { # Other foreach here... $all{$_}{...}{...} }

I know how to loop through every level, but this "breaks" the idea that it is a self contained object...

Is there a good technique to use?

thanks!

Replies are listed 'Best First'.
Re: basic object question
by mfriedman (Monk) on Jun 15, 2002 at 05:18 UTC
    Instead of using plain old hashes within your object hash, make your object hash contain other objects. Then, you could write Get and Set methods for those.

    That might be a pain, though.

    My personal preference is not to make anything beyond the first level of the object hash directly useful to the outside. I'll populate the first level with data members and write accessors and mutators for them. Then I'll do something like:

    $self->{_private}{'foo'} = Foo->new;

    I then make sure that none of my accessors or mutators will return $self->{_private}. Of course, it's not really private, but it works enough for me.

Re: basic object question
by Anonymous Monk on Jun 15, 2002 at 05:15 UTC
    check out ref, and learn recursion. Data::Dumper does something like this, so does Data::Denter. Of course both do more work that what you need, but recursion is recursion, and they're examples of it. That is all.

    Also, this has nothing to do with "objects". Its a perl data structures question. Suggested reading is perldata, perldsc, perllol, and perlref.

Re: basic object question
by BUU (Prior) on Jun 15, 2002 at 05:17 UTC
    Are you talking about something like:
    sub new { shift; my $x={@_}; }
    which allows you to do stuff like:
    my $foo=new obj(baz=>foo,bar=>quux)
    ?