0

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.

2
  • How do you generate the first hash to begin with? Commented Jan 3, 2012 at 2:11
  • How do you intend to use the values? Commented Jan 3, 2012 at 2:24

2 Answers 2

10

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Dan. I am still working on building a loop which will go over the above hash (the latter portion of your post), but the details that you provided are exactly what I was looking for !
0

Hard to tell exactly what you're looking for given the question. I suspect a hash of hashes will suffice. You'd set it up like this:

%hash = ( 'env1' => { 'server' => 'server1', 'port' => 'port1' }, 
          'env2' => { 'server' => 'server2', 'port' => 'port2' } );

To get the values, you'd do something like this:

print $hash{'env2'}->{'server'};

You can add additional values like this:

$hash{'env3'} = {'server' => 'server3', 'port' => 'port3'};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.