Connecting Tech Pros Worldwide Forums | Help | Site Map

Hashes in subroutines?

David Fass
Guest
 
Posts: n/a
#1: Feb 13 '07

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.

}

Joe Smith
Guest
 
Posts: n/a
#2: Feb 13 '07

re: Hashes in subroutines?


David Fass wrote:
Quote:
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
Closed Thread