Create secondary hashtables for fast search of values

59 Views Asked by At

I have a hashref of the following format:

{  
   introduction_to_systems => {  
                                 writer => "John",  
                                 owner => "Jim"  
   },  
   management_recipies => {  
                                 writer => "Jane",  
                                 owner => "Jim"  
   },  
etc  
}  

The issue I have is that this hash is not very convenient. I would also like to be able to find easily everything that is owned by "Jim" or "John" is the writer.

Basically I need 2 inverses of this hashtable.
What is the most efficient way to do this in perl?

1

There are 1 best solutions below

0
On

Because each owner and writer can own and write many things you has to make hash with an array of books as value. You can do it in many ways. For example:

#!/usr/bin/env perl
use strict;
use warnings;

my $books = {
    introduction_to_systems => {
        writer => "John",
        owner  => "Jim"
    },
    management_recipies => {
        writer => "Jane",
        owner  => "Jim"
    },
};

my ( %owns, %wrote );
for my $book ( keys %$books ) {
    my $rec = $books->{$book};
    push @{ $owns{ $rec->{owner} } },   $book;
    push @{ $wrote{ $rec->{writer} } }, $book;
}

print "Jim owns @{$owns{Jim}}\n";
print "John wrote @{$wrote{John}}\n";