Subroutine return two Hash

T

ThERiZla

Hi,

I have a subroutine where I create two hash and I return it. But When
I check
after the subroutine if there is something and my two hash, the first
one is correct but the second one there is nothing in.
I check the two hash before I return it and my informations are in the
two hash.


This is my code:

my (%hash1, %hash2) = createHash();

# print the two hash

sub cresteHash {

# create Two Hash

return (%hash1, %hash2);
}


Anyone can explain me the method to do this ?

Thanks
 
K

Karlheinz Weindl

ThERiZla said:
Hi,

I have a subroutine where I create two hash and I return it. But When
I check
after the subroutine if there is something and my two hash, the first
one is correct but the second one there is nothing in.
I check the two hash before I return it and my informations are in the
two hash.


This is my code:

my (%hash1, %hash2) = createHash();

# print the two hash

sub cresteHash {

# create Two Hash

return (%hash1, %hash2);
}


Anyone can explain me the method to do this ?

Use references to hashes instead.
 
G

Gunnar Hjalmarsson

ThERiZla said:
I have a subroutine where I create two hash and I return it.

sub cresteHash {
# create Two Hash
return (%hash1, %hash2);
}

That does not return two hashes. It returns one list whose elements
are the keys and values of both the hashes. Please study
http://www.perldoc.com/perl5.8.0/pod/perlsub.html
Anyone can explain me the method to do this ?

Have the subroutine return hash references instead:

my ($hashref1, $hashref2) = createHash();

print "$_ = $hashref1->{$_}\n" for keys %$hashref1;
print "\n";
print "$_ = $hashref2->{$_}\n" for keys %$hashref2;

sub createHash {
# create Two Hash
return (\%hash1, \%hash2);
}
 
G

gilgames

<<
This is my code:

my (%hash1, %hash2) = createHash();

# print the two hash

sub cresteHash {

# create Two Hash

return (%hash1, %hash2);
}


Anyone can explain me the method to do this ?
Return the references an outside dereference them

sub cresteHash {

# create Two Hash

return (\%hash1, \%hash2);
}


my ($hash1, $hash2) = createHash();
my %hash1 =%$hash1;
my %hash2 = %$hash2;
 
K

Karlheinz Weindl

gilgames said:
my ($hash1, $hash2) = createHash();
my %hash1 =%$hash1;
my %hash2 = %$hash2;

Hmm, when I said 'use references to hashes instead' then I implied to
use them on the calling side as well (e.g. as shown in Gunnar's answer).
Unless there is a good reason for it, why would you introduce a
(possible lengthy) copy operation here?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top