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?

1
  • 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. Commented Aug 23, 2015 at 14:10

1 Answer 1

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"] } }
Sign up to request clarification or add additional context in comments.

4 Comments

I create this in a loop. So basically I should not care about initializing an empty array or empty hashref?
Command to display contents of a data structure using Data::Dump. It's similar to Data::Dumper and Dumper.
@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
"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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.