Hashes in subroutines?

D

David Fass

Ok, stupid question...probably has a really stupid answer that I
can't see..
Here's the scenerio I'm pulling data from a database for different time
periods...so I set up a series of hashes in a subrutine...

Sorta like this ....

sub foo($$$$){
my %hash1 = {};
my %hash2 = {};
my %hash3 = {};
#...pull out data..populate hash1 and hash2 ....#
# e.g if ($sx eq "M"){ $hash2{$age}++;}
foreach $key ( sort keys %hash1){
$hash3->{$key}++;
}
foreach $key (sort keys %hash2){
$hash3->{$key}++;
}
foreach $x (sort keys %{$hash3}){
print "$x\t$hash1{$x}\t$hash2{$x}\n";
}

Now the bugger is that I get phantom keys and wierd 0's....
e.g hypothetically if hash1 is supposed to contain undef for iteration
1, 22 and 38 for iteration 2, and 46 and 78 for iteration 3...
I'd get output for iteration 3
22 0 0
38 0 0
46 1 0
78 0 1
0 0 0
0 0 0
0 0 0

dumping the hash1 and hash2 using Data:::dump I'd get
hash1 (46,1,HASH(XXXX),undef);
hash2(78,1,HASH(XXXX),undef);

Now how do I zero the hash, including the keys...
since I keep getting the old keys from previous iterations.

In a test file I tried using undef(%hash) and %hash=() with similar
results.

}
 
J

Joe Smith

David said:
my %hash1 = {};
my %hash2 = {};
my %hash3 = {};
#...pull out data..populate hash1 and hash2 ....#
# e.g if ($sx eq "M"){ $hash2{$age}++;}
foreach $key ( sort keys %hash1){
$hash3->{$key}++;
}
foreach $key (sort keys %hash2){
$hash3->{$key}++;
}
foreach $x (sort keys %{$hash3}){
print "$x\t$hash1{$x}\t$hash2{$x}\n";
}

Everywhere except on the third line, $hash3 is a reference to a hash.
On line three, you have a totally different variable: %hash3.

my $hashref = {};
$hashref->{$_}++ for keys %hash1;
$hashref->{$_}++ for keys %hash2;
print "$_\t$hash1{$_}\t$hash2{$_}\n" for sort keys %{$hashref};

-Joe
 

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,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top