in reply to Re^4: csv to hash table
in thread csv to hash table
We really need to see the output. I see a potential problem here in that you are stashing “a reference to @array” ... while that is a single variable. Hence, all of the references will be to the same block of storage, namely, @array. In Fortran parlance, all of the references are EQUIVALENCEd. They will all be seen to contain the last contents of @array, and a change to any one will be reflected in every other, because “you are actually looking at one block of storage, albeit through several mirrors.
I think that you need to be sure that each hash-bucket contains a uniquehashref, and that the values get pushed onto that. Perl’s “auto-vivification” feature comes in handy, with something like this:
gives ...use strict; use warnings; use Data::Dumper; my @arry = ( "key", 1, 2, 3 ); my $hash; my $key = shift @arry; # NEXT STATEMENT 'AUTOMAGICALLY' CREATES A HASH-ENTRY FOR $key # AND CAUSES IT TO CONTAIN AN EMPTY ARRAY IF IT # DOES NOT ALREADY EXIST: push @{ $hash->{$key} }, $_ foreach @arry; print Data::Dumper->Dump([ \@arry, $hash], ["arry", "hash"] );
$arry = [ 1, 2, 3 ]; $hash = { 'key' => [ 1, 2, 3 ] };
The foreach clause is shorthand for an equivalent loop. $_ contains the value within each iteration. Notice how this loop is non-destructive to the content of @arry, iterating through its values without disturbing them. The magic works now, because we are making copies of each value and pushing those onto a new arrayref (created on-demand) within the hash-bucket for $key. Each hash-bucket, and each of the values therein, is distinct.
In the statement-of-interest, @{ ... } is part but not all of the magic. Here, we are telling Perl that the value within the hash-bucket should be interpreted as / initialized to an arrayref. Perl will automatically create a hash-entry (of course) on demand, because that is what hashes do, but here we’re declaring its type and immediately using it. We can “auto-vivify” hashrefs, too, so that a line of code something like this ... actually Just Works™:
gives...$hash->{"hickory"}{"dickory"}{"dock"} = "clock";
$hash = { 'hickory' => { 'dickory' => { 'dock' => 'clock' } } };
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: csv to hash table
by choroba (Cardinal) on Nov 19, 2013 at 15:42 UTC | |
|
Re^6: csv to hash table
by waytoperl (Beadle) on Nov 19, 2013 at 18:40 UTC | |
by ig (Vicar) on Nov 20, 2013 at 19:44 UTC |