tags:

views:

100

answers:

2

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";
    }
}
+10  A: 

$files{$key} will indeed return the value of that key. But what if that value happens to be false in a boolean context, like 0 or '' (an empty string)?

Consider a hash like this:

my %foo = ( red => 42, blue => 0, green => '', yellow => undef );

If I were to say if ( $foo{blue} ) the condition would fail. Even though blue exists in the hash, the condition is false because the value of $foo{blue} is zero. Same with the green and yellow keys -- empty strings and undef are 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 call keys and then grep the resulting list, but that's ridiculous.)

Your code looks perfectly fine to me. You are using exists correctly.

friedo
@friedo I realised it was some syntax errors that was giving me issues, but thanks for that clarification, makes things a lot clearer!
Aaron Moodie
+4  A: 

exists $hash{key} says if the key exists, defined $hash{key} says if the key exists and its value is defined, $hash{key} says if the key exists and its value is true (see http://perldoc.perl.org/perlsyn.html#Truth-and-Falsehood).

codeholic