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

I've been trolling and searching, but have not found anything that helps me. If you know of a thread please link me. I have a structure containing a hash. I want to pass the structure into a sub by reference. While in the sub, I want access to the hash. Please cure my stupidity. heres a stripped down example:
use Class::Struct; struct MyStruct => { hash1 => '%', }; #fill the struct's hash with some data my $test = MyStruct->new( hash1=>{one=>onesdata} ); use_hash(\$test); while(($key,$val) = each %{$test->hash1}){ print "$key=$val\n"; } sub use_hash{ my $ref = shift; #obtain the passed in reference $$ref->hash1{two} = 'twosdata'; #PROBLEM }
I get an error on the line marked problem. Can anyone explain my error? Many thanks in advance.

Replies are listed 'Best First'.
Re: passing object references into subs
by dbp (Pilgrim) on Feb 03, 2003 at 18:50 UTC

    Ok. Two problems.

    First of all, $test is already a reference, so you don't need to pass a reference to the reference to use_hash. If, for some reason, this is what you intended, you're going to need to dereference $ref twice in use_hash. Otherwise change

    use_hash(\$test);
    to
    use_hash($test);

    Secondly, assuming you've made the change above, change line 19 to:

    %{$ref->hash1}->{'two'} = 'twosdata';
    If you haven't made the change above, you'll have to nest a dereference of $ref into this statement, like so:
    %{$$ref->hash1}->{'two'} = 'twosdata';

      ah! dbp++! I did not realize test was already a reference, although I guess that makes sense. I understand how references work, but get hung up on the perl syntax. Many thanks dbp!