How do I check if a key exists in a hash in Perl? [duplicate]
Question
This question already has an answer here:
I want to check if parameter $PGkey
is equal to a key with the same name inside a hash table. Further, I want to do it in a format as close to this as possible:
while(<PARAdef>) {
my($PGkey, $PGval) = split /\s+=\s+/;
if($PGkey == $hash{$PGkey}) {
print PARAnew "$PGkey = $hash{$PGkey}->[$id]\n";
} else {
print PARAnew "$PGkey = $PGval\n";
}
}
Is there a simple way to do it?
Solution
Using the conditional operator lets you factor out the common code in that if/else statement:
while ( <PARAdef> ) {
chomp;
my ($PGkey, $PGval) = split /\s+=\s+/;
print "$PGkey = ",
$PGval eq $hash{$PGkey}[$id] ? $hash{$PGkey}[$id] : $PGval, "\n";
}
Or if you just misstated the problem and really want to use $hash{$PGkey}[$id] if $hash{$PGkey} exists and fall back to $PGval if it doesn't, then you can say
while ( <PARAdef> ) {
chomp;
my ($PGkey, $PGval) = split /\s+=\s+/;
print "$PGkey = ",
$PGkey ne "def" and exists $hash{$PGkey} ?
$hash{$PGkey}[$id] : $PGval, "\n";
}
A quick note, you seem to be using the old bareword style filehandles. The new (if ten years old can be considered new) lexical filehandles are superior in every way:
open my $PARAdef, "<", $filename
or die "could not open $filename: $!";
OTHER TIPS
The way to check for hash key existence is:
exists $hash{$key}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow