Search code examples
perlperl-data-structures

Perl array of hash structures


This is a design setup question. I know in Perl there are not array of arrays. I am looking at reading in code that pulls in data from large text files at phases of something in flight. Each of these phases track different variables (and different numbers of them) . I have to store them because in the second part of the script i am rewriting them into another file I am updating as I read in.

I thought first I should have an array of hash's, however the variables are not the same at each phase. Then I thought maybe and array with the name of several arrays (array of references I guess) .

Data example would be similar to

phase 100.00  mass 0.9900720175260495E+005 
phase 240.00  gcrad 61442116.0 long 0.963710076E+003 gdalt 0.575477727E+002 vell 0.9862937759999998E+002

Data is made up but you should get the idea and there would be many phases and the variable would likely range from 1 to 25 variables in each phase


Solution

  • You can use Arrays of Arrays in Perl. You can find documentation on Perl data structures including Arrays of Arrays here: http://perldoc.perl.org/perldsc.html. That said, looking at the sample you've provided it looks like what you need is an Array of Hashes. Perhaps something like this:

    my @data = (
      { phase => 100.00,
        mass  => 0.9900720175260495e005 },
      { phase => 240.00
        gcrad => 61442116.0
        long  => 0.963710076e003
        gdalt => 0.575477727e002
        vell  => 0.9862937759999998e002 }
    );
    

    to access the data you would use:

    $data[0]->{phase} # => 100.00
    

    You could also use a Hash of Hashes like this:

    my %data = (
      name1 => { 
        phase => 100.00,
        mass  => 0.9900720175260495e005
      },
      name2 => {
        phase => 240.00
        gcrad => 61442116.0
        long  => 0.963710076e003
        gdalt => 0.575477727e002
        vell  => 0.9862937759999998e002
      }
    );
    

    to access the data you would use:

    $data{name1}->{phase} # => 100.00
    

    A great resource for learning how to implement advanced data structures and algorithms in Perl is the book, Mastering Algorithms in Perl