Reputation: 3
Some problems with hashing as I move to Perl 5 on a new server:
I have a hash called %hash that appears full of word=>family pairs (went=>go) when I test it thus:
while ( my ($key, $value) = each(%hash)) { print " $key => $value\n"; }
However, when I try to get the value for a given key ~
if ( $hash{$word} ) {...
~ the output is nil even when I know it cannot be! There must be something obviously wrong with this but I am looking my eyes out
Upvotes: 0
Views: 133
Reputation: 5083
To see if $word
is malformed, try doing:
use Data::Dumper ;
sub test
{
my ($hashref, $key) = @_ ;
print "Before: " . Dumper( $hashref ) ;
if ( $key ~~ $hashref ) { print "found $key : $hashref->{$key}\n" ; }
else
{
$hashref->{$key} = "NOT FOUND" ;
print "After: " . Dumper( $hashref ) ;
}
}
Then look to see what's different in the two hashes.
Upvotes: 0
Reputation: 3069
Since you didn't give a detailed description of code, I can just infer your problem:
1.Your hash actually didn't have a key $word.Please check it.
2.The value for key $work is just an empty string "" or an number 0 or "\0",all these conditions will lead your if($hash{$word}) return false even though your hash for this key has values.So ,check it again.
Upvotes: 3
Reputation: 385917
However, when I try to get the value for a given key (
if ( $hash{$word} ) {...
) the output is nil
if ( $hash{$word} )
is not how you print the value of a hash element. print $hash{$word};
is.
Upvotes: -2