Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Dereferencing a portion of a hash

by THRAK (Monk)
on Feb 18, 2005 at 15:58 UTC ( [id://432371]=perlquestion: print w/replies, xml ) Need Help??

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

I have a large hash from which I want to pass a portion of it to a subroutine. My problem is, how do I dereference it within the subroutine?
report_block(\$report_data{$domain}{$provider}); sub report_block { my ($rpt_ref) = shift; print Dumper($rpt_ref); #access elements here! }
That dump yields:
$VAR1 = \{ 'error' => 0, 'total' => 7, 'soft_error' => 0, 'hard_error' => 0, 'ok' => 7 };
But I can't seem to figure out how to access the individual elements. After searching around I've tried the following, but neither of them are what I need.
print $rpt_ref{total}; #Global symbol "%rpt_ref" requires explicit package name... print $rpt_ref->{total}; #Not a HASH reference at...
Obviously something escapes me here. ;)

Replies are listed 'Best First'.
Re: Dereferencing a portion of a hash
by tall_man (Parson) on Feb 18, 2005 at 16:08 UTC
    What you have passed is a reference to a reference. If you do this instead:
    report_block($report_data{$domain}{$provider}); sub report_block { my ($rpt_ref) = shift; print Dumper($rpt_ref); #access elements here! print $rpt_ref->{total}; }
    Then you will have a simple hash reference and the arrow notation will work.
      Maybe this is a stupid question, but how is that passing a reference as a reference? Isn't what you've done (which does work) pass a copy of that portion of the hash? Or is it such that when you pass a portion of a hash it automagically passes it as a reference?
        $report_data{$domain}{$provider} is a hash reference already. This is shown by your data dumper (which shows that it contains hash key/values).

        You are then taking the reference to that hash reference by passing it as \$report_data{$domain}{$provider} which makes it a reference to a reference.

        Hence, you need to either not pass it that way or dereference it twice.

        $,=" : ";$\="\n"; print $_, $$rpt_ref->{$_} for keys %{$$rpt_ref};
        --------------
        It's sad that a family can be torn apart by such a such a simple thing as a pack of wild dogs
Re: Dereferencing a portion of a hash
by Anonymous Monk on Feb 18, 2005 at 16:27 UTC
    print $$rpt_ref->{total}; print $$$rpt_ref{total};

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://432371]
Approved by Tanktalus
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-03-29 13:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found