I’ve been reading over the perl doc, but I can’t quite get my head around hashes. I’m trying to find if a hash key exists, and if so, compare its value. The thing that is confusing me is that my searches say that you find if a key exists by if (exists $files{$key}), but that $files{$key} also gives the value? the code I’m working on is:
foreach my $item(@new_contents) {
next if !-f "$directory/$item";
my $date_modified = (stat("$directory/$item"))[9];
if (exists $files{$item}) {
if ($files{$item} != $date_modified {
$files{$item} = $date_modified;
print "$item has been modified\n";
}
} else {
$files{$item} = $date_modified;
print "$item has been added\n";
}
}
$files{$key}will indeed return the value of that key. But what if that value happens to be false in a boolean context, like0or''(an empty string)?Consider a hash like this:
If I were to say
if ( $foo{blue} )the condition would fail. Even thoughblueexists in the hash, the condition is false because the value of$foo{blue}is zero. Same with thegreenandyellowkeys — empty strings andundefare false values.Without
exists, there would be no (easy) way to determine if a hash key actually is actually there and its value is false, or if it’s not there at all. (You could callkeysand thengrepthe resulting list, but that’s ridiculous.)Your code looks perfectly fine to me. You are using
existscorrectly.