Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

return multiple hashes from a sub

by rsiedl (Friar)
on Feb 03, 2005 at 14:17 UTC ( [id://427645]=perlquestion: print w/replies, xml ) Need Help??

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

Hi Monks,

Can anyone tell me if it's possible/and how to return multiple hashes from a sub routine?
Something like below (this isnt working):
#!/usr/bin/perl use strict; my (%hash1, %hash2) = &build_hashes; foreach (keys (%hash1)) { print $_, ":", $hash1{$_}, "\n"; } # end-foreach foreach (keys (%hash2)) { print $_, ":", $hash2{$_}, "\n"; } # end-foreach sub build_hashes { my %hash1 = { 1=>"foo1", 2=>"bar1" }; my %hash2 = { 3=>"foo2", 4=>"bar2" }; return (\%hash1, \%hash2); } # end-sub exit;

Cheers,
Reagen

Replies are listed 'Best First'.
Re: return multiple hashes from a sub
by monkey_boy (Priest) on Feb 03, 2005 at 14:28 UTC
    You need to read about references,
    but heres the answer ...
    my ($hash1, $hash2) = &build_hashes; foreach (keys (%{$hash1})) { print $_, ":", $hash1->{$_}, "\n"; } # end-foreach foreach (keys (%{$hash2})) { print $_, ":", $hash2->{$_}, "\n"; } # end-foreach sub build_hashes { my %hash1 = ( 1=>"foo1", 2=>"bar1" ); my %hash2 = ( 3=>"foo2", 4=>"bar2" ); return (\%hash1, \%hash2); } # end-sub exit;



    Im so sick of my Signature...
Re: return multiple hashes from a sub
by pelagic (Priest) on Feb 03, 2005 at 14:31 UTC
    Your initialising was wrong; use:
    my %hash1 = ( 1=>"foo1", 2=>"bar1" ); ## instead if my %hash1 = { 1=>"foo1", 2=>"bar1" };
    ... no curlies!

    pelagic
Re: return multiple hashes from a sub
by chb (Deacon) on Feb 03, 2005 at 14:32 UTC
    Try dereferencing the hash references you get from your sub: foreach (keys %$hash1) { ... }.
Re: return multiple hashes from a sub
by aquarium (Curate) on Feb 03, 2005 at 14:24 UTC
    The modular approach calls for a build_hash sub, which gets called with parameters (twice) to build each hash, and return a reference to that. if you programmed this in OO style, it would be similar to the modular -- divide and conquer -- approach. The other way is to return a reference to an anonymous hash/array of hashes. just a little different to dereference then.
    the hardest line to type correctly is: stty erase ^H

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2024-04-19 10:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found