keys, values, exists and delete

keys and values

keys returns the list of keys, values returns the list of values, and both come back in the same internal order. Walk one list and index the hash when you need the pair.

my %user = (name => "Ada", age => 36); for my $key (sort keys %user) { print "$key = $user{$key}\n"; } print scalar keys %user, "\n"; # 2

perl demo.pl

age = 36
name = Ada
2

In scalar context keys returns a count, not a list. That is why the usual test for an empty hash is if (keys %h).

exists and defined

exists asks whether a key is present; defined asks whether its value is a real value. A key can exist and hold undef at the same time, so the two questions are different.

my %user = (name => "Ada", age => 36); $user{phone} = undef; print "key present\n" if exists $user{phone}; print "no value yet\n" unless defined $user{phone};

perl demo.pl

key present
no value yet

Without exists, reading a missing key in a condition autovivifies it, as lesson 11 warned. Reach for exists whenever a wrong branch would change the data.

delete

delete removes the pair and returns the value that was stored, which makes it useful for draining a table one entry at a time. Deleting a missing key is not an error; it returns undef.

my %user = (name => "Ada", age => 36, phone => undef); my $old = delete $user{age}; print "removed $old\n"; # removed 36 print "keys: ", scalar keys %user, "\n"; # keys: 2

perl demo.pl

removed 36
keys: 2

To empty a whole hash at once, assign an empty list: %user = (); That is faster than deleting key by key and keeps the variable declared.

Invert a hash

Swapping keys and values is a single expression, because a hash assigned from a list takes alternating key and value. Duplicate values collapse, so invert only when values are unique.

my %by_id = ( a => 1, b => 2, ); my %by_num = reverse %by_id; print $by_num{2}, "\n"; # b

perl demo.pl

b

reverse on a hash flattens it to key-value pairs, flips them, and the assignment rebuilds a hash. One built-in, no loop.

Next: Scalar and list context

Article author: Arthur Isaev

Banner image