Perl FAQ 5.3: How do I make an array of structures containing various data types?

Perl FAQ 5.3

How do I make an array of structures containing various data types?

This answer will work under perl5 only. Did we mention that you should upgrade? There is a perl4 solution, but you are using perl5 now, anyway, so there's no point in posting it. Right?

The best way to do this is to use an associative array to model your structure, then either a regular array (AKA list) or another associative array (AKA hash, table, or hash table) to store it.

    %foo = (
               'field1'        => "value1",
               'field2'        => "value2",
               'field3'        => "value3",
               ...
           );
    ...

    @all = ( \%foo, \%bar, ... );

    print $all[0]{'field1'};

Or even

    @all = (
       {
           'field1'        => "value1",
           'field2'        => "value2",
           'field3'        => "value3",
           ...
       },
       {
           'field1'        => "value1",
           'field2'        => "value2",
           'field3'        => "value3",
           ...
       },
       ...
    )

Note that if you want an associative array of lists, you'll want to make assignments like

    $t{$value} = [ @bar ];

And with lists of associative arrays, you'll use

    %{$a[$i]} = %old;

Study these for a while, and in an upcoming FAQ, we'll explain them fully:

    $table{'some key'}    =   @big_list_o_stuff;   # SCARY #0
    $table{'some key'}    =  \@big_list_o_stuff;   # SCARY #1
    @$table{'some key'}   =   @big_list_o_stuff;   # SCARY #2
    @{$table{'some key'}} =   @big_list_o_stuff;   # ICKY RANDALIAN CODE
    $table{'some key'}    = [ @big_list_o_stuff ]; # same, but NICE

And while you're at it, take a look at these:

    $table{"051"}         = $some_scalar;          # SCARY #3
    $table{"0x51"}        = $some_scalar;          # ditto
    $table{051}           = $some_scalar;          # ditto
    $table{0x51}          = $some_scalar;          # ditto
    $table{51}            = $some_scalar;          # ok, i guess
    $table{"51"}          = $some_scalar;          # better

    $table{\@x}           = $some_scalar;          # SCARY #4
    $table{[@x]}          = $some_scalar;          # ditto
    $table{@x}            = $some_scalar;          # SCARY #5 (cf #0)

See perlref(1) for details.


Other resources at this site: