Amelio Vazquez-Reina
Amelio Vazquez-Reina

Reputation: 96300

Grabbing a list from a multi-dimensional hash in Perl

In Programming Perl (the book) I read that I can create a dictionary where the entries hold an array as follows:

$wife{"Jacob"} = ["Leah", "Rachel", "Bilhah", "Zilpah"];

Say that I want to grab the contents of $wife{"Jacob"} in a list. How can I do that?

If I try:

$key = "Jacob";
say $wife{$key};

I get:

ARRAY (0x56d5df8)

which makes me believe that I am getting a reference, and not the actual list.

Upvotes: 1

Views: 120

Answers (2)

Vijay
Vijay

Reputation: 67231

I guess by this time you must be knowing that $ refers to a scalar and @ refers to an array.

since you yourself said that the value for that key is an array,then you should

say @wife{$key};

instead of

say $wife{$key};

Upvotes: 1

amon
amon

Reputation: 57640

See

for information on using complex data structures and references.

Essentially, a hash can only have scalars as values, but references are scalars, Therefore, you are saving an arrayref inside the hash, and have to dereference it to an array.

To dereference a reference, use the @{...} syntax.

say @{$wife{Jacob}};

or

say "@{$wife{Jacob}}"; # print elements with spaces in between

Upvotes: 4

Related Questions