Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Adding to hash that contains an array of arrays

by eppo (Novice)
on Jan 29, 2014 at 20:03 UTC ( #1072573=perlquestion: print w/replies, xml ) Need Help??
eppo has asked for the wisdom of the Perl Monks concerning the following question:

I'm hoping someone could help me out with this, I'm trying to create a structure like this:

%hash{ ID => [  [1,2,3,4,5],[1,2,3,4,5]  ] }

what i'm doing is iterating over the rows of a database table, for each row, I want to add it to that inner array. , so if i added another row it would look like this:

%hash{ ID => [ [1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]  ] }

I'm having trouble wrapping my head around it. how would I add @ARRAY to the hash? Thanks

Replies are listed 'Best First'.
Re: Adding to hash that contains an array of arrays
by moritz (Cardinal) on Jan 29, 2014 at 20:14 UTC
Re: Adding to hash that contains an array of arrays
by rnewsham (Chaplain) on Jan 29, 2014 at 20:16 UTC

    Here is some code that I think produces the data structure you want. However it sounds like there may be a better structure or approach to achieve the desired result. Perhaps if you provide more of your code and a clearer description of what you are trying to achieve we may be able to offer more helpful suggestions.

    use strict; use warnings; use Data::Dumper; my %hash; for my $i ( 1 .. 3 ) { my @array; for my $j ( 1 .. 3 ) { push @array, $j; } push @{ $hash{ID} }, \@array; } print Dumper( %hash );
    Output $VAR1 = 'ID'; $VAR2 = [ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ];

      What i'm trying to do is this, I have an sql table, in the table, there are 2 columns that contain user id's. I'm trying to collect the data for each of the id's. this data was going to be written to an xlsx file. the data needed to create the xlsx file is an array of arrays. so i was thinking about making a hash, that contains each of the id's, and then for each of those id's it points to an array of arrays that I can use to create the spreadsheet. Is there some other way that would be more elegant to get this done?

        Where you get the data from is irrelevant, the "push" demonstrated by both moritz and mewsham manipulates your data structure in exactly the way you're asking for.

        It adds an array reference (what an array of arrays really contains) to the array in your hash.

        -- FloydATC

        Time flies when you don't know what you're doing

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1072573]
Approved by rnewsham
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2017-02-24 04:03 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (351 votes). Check out past polls.