Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials

invert a hash

( categories: )

Use reverse to invert a hash.

%inverted = reverse %hash;

Notes:

  • If the original hash has duplicated values (more than one key is mapped to the same value) then the reversed hash will have fewer elements, because the duplicated value will only map to only one of the keys.
  • This operation can be very expensive in terms of processing time and memory usage if the hash to be inverted is very large.

sort a hash

( categories: )

The idea is to sort the list of keys of the hash and iterate through the sorted list using a 'foreach' statement.

-- order by key alphabetically

foreach my $key ( sort keys %hash )
{
  print "key: " . $key . " value: " . $hash{$key} . "\n";
}

-- order by key numerically

foreach my $key ( sort { $a <=> $b } keys %hash )
{
  print "key: " . $key . " value: " . $hash{$key} . "\n";
}

-- order by value alphabetically


iterate through a hash

( categories: )

There are 2 methods:

- Using 'keys' in a 'foreach' loop

foreach my $key ( keys %hash )
{
  print "key: $key, value: $hash{$key}\n";
}

This method has the advantage that it's possible to sort the output by key.

The disadvantage is that it creates a temporary list to hold the keys, in case your hash is very large you end up using lots of memory resources.

- Using 'each' in a 'while' loop

while ( ($key, $value) = each %hash )
{
  print "key: $key, value: $hash{$key}\n";
}

This method's advantage is that it uses very little memory (every time 'each' is called it only returns a pair of (key, value) element).


check if a key exists in a hash

( categories: )

Use the function exists

print "Key $key exists\n" if ( exists($hash{$key}) );


get the keys of a hash

( categories: )

@list = keys %hash;

Explanation:
The code above stores all the keys of hash '%hash' in the list '@list'


get the values of a hash

( categories: )

@list = values %hash;

Explanation:

The code above stores all the values of hash '%hash' in the list '@list'


remove a hash element

( categories: )

delete $hash{"key"};


empty a hash

( categories: )

%hash = ();


Syndicate content