O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding an Element to a Hash

Problem

You need to add an entry to a hash.

Solution

Simply assign to the hash key:

$HASH{$KEY} = $VALUE;

Discussion

Putting something into a hash is straightforward. In languages that don’t provide the hash as an intrinsic data type, you have to worry about overflows, resizing, and collisions in your hash table. In Perl, all that is taken care of for you with a simple assignment. If that entry was already occupied (had a previous value), memory for that value is automatically freed, just as when assigning to a simple scalar.

# %food_color defined per the introduction
$food_color{Raspberry} = "pink";
print "Known foods:\n";
foreach $food (keys %food_color) {
    print "$food\n";
}


                  Known foods:
               
                  Banana
               
                  Apple
               
                  Raspberry
               
                  Carrot
               
                  Lemon

If you store undef as a hash key, it gets stringified to "" (and generates a warning if your program is running under -w). Using undef as a key is probably not what you want. On the other hand, undef is a valid value in a hash. But if you fetch the value for a key that isn’t in the hash, you’ll also get undef. This means you can’t use the simple Boolean test if ($hash{$key}) to see whether there is an entry in %hash for $key. Use exists($hash{$key}) to test whether a key is in the hash, defined($hash{$key}) to test if the corresponding value is not undef, and if ($hash{$key}) to test if the corresponding value is a true value.

In Perl’s hashing algorithm, permutations of a string hash to the same spot internally. If your hash contains ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required