Grabbing a list from a multi-dimensional hash in P

2019-08-02 07:02发布

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.

2条回答
放荡不羁爱自由
2楼-- · 2019-08-02 07:26

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
查看更多
一夜七次
3楼-- · 2019-08-02 07:37

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};
查看更多
登录 后发表回答