Search code examples
perldata-structureshashperl-data-structures

Perl query about data structure


I currently use the following hash which works fine

%hash = ( 
    'env1' => 'server1:port1, server11:port11',
    'env2' => 'server2:port2, server22:port22'
) ;

However, what I really want to do is create the following data structure, which will make it easier for me to extract the information. The following obviously does not work.

(
  env1 => "server=server1, port=port1", "server=server11, port=port11",
  env2 => "server=server2, port=port2", "server=server22, port=port22"
) ;

Wondering if anyone has any suggestions on creating a data structure that would match my requirements.


Solution

  • Write this:

    %hash = (
      env1 => ["server=server1, port=port1", "server=server11, port=port11"],
      env2 => ["server=server2, port=port2", "server=server22, port=port22"]
    ) ;
    

    And then access elements like this:

    $hash{'env1'}->[0] == "server=server1, port=port1"
    $hash{'env2'}->[1] == "server=server22, port=port22"
    

    This is a hash where the values are references to anonymous arrays.

    But when I look at you data I think maybe there is a better way to store it:

    %hash = (
      env1 => [{'server' => 'server1', 'port' => 'port1'}, {'server' => 'server11', 'port' => 'port11'}],
      env2 => [{'server' => 'server2', 'port' => 'port2'}, {'server' => 'server22', 'port' => 'port22'}]
    ) ;
    

    And then access elements like this:

    $hash{'env1'}->[0]->{'server'} == "server1"
    $hash{'env2'}->[1]->{'port'} == "port22"