The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


Tie::Hash::TwoWay - Perl extension for two-way mapping between two disjoint sets


  use Tie::Hash::TwoWay;
  tie %hash, 'Tie::Hash::TwoWay';

  my %list = (
              Asimov => ['novelist', 'scientist'],
              King => ['novelist', 'horror'],

  foreach (keys %list)                  # these are the primary keys of the hash
   $hash{$_} = $list{$_};

  $hash{White} = 'novelist';
  $hash{White} = 'color';

  # these will all print 'yes'
  print 'yes' if exists $hash{scientist};
  print 'yes' if exists $hash{novelist}->{Asimov};
  print 'yes' if exists $hash{novelist}->{King};
  print 'yes' if exists $hash{novelist}->{White};
  print 'yes' if exists $hash{King}->{novelist};

  my $secondary = scalar %hash;
  print "Secondary keys: ";
  print "$_\n" foreach keys %$secondary;


Tie::Hash::TwoWay will take a list of one-way associations and transparently create their reverse. For instance, say you have a list of machines, and a list of classes that each machine belongs to. Tie::Hash::TwoWay will take the machines, one by one, with an associated array reference of class names, and build the reverse mapping of classes to machines. All the mappings are stored as hashes. You can access the secondary mappings as if they were hash keys in their own right.

Deleting a key in either the forward or reverse mapping will delete all its mappings in the other direction as well. If a key has no more mappings, the key itself is deleted as well. For example, if you delete machine "joe" that was in class "extra", and there are no other machines in class "extra", that class will be automatically deleted as well.

Peculiarities, which might be considered bugs:

Duplicate keys, overlapping between the primary and the secondary, are allowed (for instance, a class named the same as a machine). Fetching a key, checking for its existence, and deleting it will go to the primary mapping first and then to the secondary.

The keys of the TwoWay hash are the keys of the primary mapping. The reverse mapping (which is just a hash reference) can be obtained by using the scalar operator on the tied hash.

Everything is stored in hashes for faster access, at the expense of memory.




Teodor Zlatanov <>



perldoc Tie::Hash perldoc Tie::StdHash