http://www.perlmonks.org?node_id=464229

Ninthwave has asked for the wisdom of the Perl Monks concerning the following question:

The many ways of perl sometimes leave me struggling when facing what is considered complex data structures.

I have a list of items represented by a unique number. Entries for this item may be duplicated. So I want to create hash with a key of the items id number.

I then want the value to be an anonymous array that lists the entry id. So that my final data structure is a hash with a key for each unique item. The value will lead me to see the individual entries on that item.

Now comes coding it. I have decided that routine to build the hash should exist in a sub, and for future portabibility it should use the hash by reference. At this point my idea of notation gets tossed around.

So my question is based on the sketch above and the code below what is the best way to write this:

sub ReadSource{ my $DataSource = shift; my $HashRef = shift; foreach my $ItemID (@Data){ #Note @Data is not globally + fed into the sub I have skipped the Data code to focus on the proble +m. if (exists($$HashRef{$ItemID})){ push @{$$HashRef{$ItemID}}, $DataSource; }else{ $$HashRef{$ItemID} = [$DataSource]; } } }

I haven't tested the code as this structure just looks unpleasent. I used as reference (all puns intended as usual) Perl Objects, Reference & Modules Chapter 4 page 40 and the code on Autovivification. I am just wondering as I prefer indirect notation if there is a way to clean this up. I am going to test my code now but was throwing the question out to the perl community to see if I as usual am missing the bleeding obvious.


"No matter where you go, there you are." BB