2

I want to dynamically create a structure as follows:

{  
   edition1 => {  
                 Jim => ["title1", "title2"],  
                 John => ["title3", "title4"],  
              },  
  edition2 => { 
                 Jim => ["titleX",],  
                 John => ["titleY,],  
              }  etc
}  

I am confused on how I do it.
Basically I am thinking in the terms of:

my $edition = "edition1";  
my $author = "Jim";  
my $title = "title1";  
my %main_hash = ();  

${$main_hash{$edition}} ||= {};   

${$main_hash{$edition}}->{$author} ||= [];     

push @{{$main_hash{$edition}}->{$author}} , $title;   

But somehow I am not sure how I can do it properly and the syntax seems very complex.
How can I achieve what I want in a nice/clear manner?

Jim
  • 18,826
  • 34
  • 135
  • 254
  • What's the purpose behind this structure? It looks like an odd sort of shape, as if you're trying to do something else with it like create JSON. – Sobrique Aug 23 '15 at 14:10

1 Answers1

3

You have made it rather hard for yourself. Perl has autovivication which means it will magically create any necessary hash or array elements for you if you use them as if they contained data references

Your line

push @{{$main_hash{$edition}}->{$author}} , $title;

is the closest you came, but you have an extra pair of braces around $main_hash{$edition} which attempts to create an anonymous hash with $main_hash{$edition} as its only key and undef as the value. You also don't need to use the indirection arrow between closing and opening brackets or braces

This program shows how to use Perl's facilities to write this more concisely

use strict;
use warnings;

my %data;

my $edition = "edition1";
my $author  = "Jim";
my $title   = "title1";

push @{ $data{$edition}{$author} }, $title;

use Data::Dump;
dd \%data;

output

{ edition1 => { Jim => ["title1"] } }
Borodin
  • 126,100
  • 9
  • 70
  • 144
  • I create this in a loop. So basically I should not care about initializing an empty array or empty hashref? – Jim Aug 23 '15 at 13:58
  • Command to display contents of a data structure using `Data::Dump`. It's similar to `Data::Dumper` and `Dumper`. – Sobrique Aug 23 '15 at 14:10
  • @Jim: Correct. Perl will look after setting up anonymous data structures for you as necessary. `dd` is the subroutine exported by `Data::Dump` to display the data you pass to it nicely – Borodin Aug 23 '15 at 14:35
  • *"I create this in a loop"* I thought as much. Your question gave me very little to work with, and it is very late in the day to admit to its shortcomings. I hope you can gain from this experience that it is better to express your question well than to rely on the analytical skills of those who may read it – Borodin Aug 23 '15 at 21:25