1

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?

Jim
  • 18,826
  • 34
  • 135
  • 254
  • Could you indicate expected number of entries and how do you fill the hash? IMHO it may affect the best option. – AnFi Aug 21 '15 at 21:25
  • @Andrzej A. Filip: 3-4K entries. What do you mean how do I fill the hash? – Jim Aug 22 '15 at 19:23
  • How do you fill empty hash with 4K entries? BTW Have you considered using "in memory" SQLite database? [It may make some sense with 4K entries] – AnFi Aug 23 '15 at 03:10

1 Answers1

1

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";
Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73