Grabbing a list from a multi-dimensional hash in P

2019-08-02 07:30发布

问题:

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.

回答1:

See

  • perllol,
  • perldsc and
  • perlreftut

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


回答2:

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};