[ Team LiB ] Previous Section Next Section

Recipe 5.1 Adding an Element to a Hash

5.1.1 Problem

You need to add an entry to a hash.

5.1.2 Solution

Simply assign to the hash key:

$HASH{$KEY} = $VALUE;

5.1.3 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 don't want to overwrite an existing value, but somehow have one key reference multiple values, see Recipe 5.8 and Recipe 11.2.

5.1.4 See Also

The "List Value Constructors" section of perldata(1); the "List Values and Arrays" section of Chapter 2 of Programming Perl; Recipe 5.2

    [ Team LiB ] Previous Section Next Section