Ricky
Ricky

Reputation: 2907

Perl - Assign an array to another variable

I'm trying to assign an array to a value in my hash as follows:

$authors->[$x]->{'books'} = @books;

$authors is an array of hashes that contains his/her first name, last name, date of birth, etc. And now I'm creating a books key where I want to assign an array of books. However, when I try to print it afterwords, it's just printing the size of the array, as if I'm doing $value = scalar @books.

What am I doing wrong?

Upvotes: 2

Views: 3508

Answers (2)

lamchob
lamchob

Reputation: 80

While the first awnser is absolutely right, as an alternative, you could also fo this:

push @{$authors->[$x]->{'books'}}, @books;

Then $authors->[$x]->{'books'} will be an Array that contains a copy of all the elements from @books. This might be more "foolproof" then working with references, as mentioned above.

Upvotes: 2

user2404501
user2404501

Reputation:

Array elements and hash values are scalars, so when you are nesting arrays and hashes, you must use references. Just as $authors->[$x] is not a hash but a reference to a hash, you must set $authors->[$x]->{'books'} to a reference to the array.

$authors->[$x]->{'books'} = \@books; # reference the original array
$authors->[$x]->{'books'} = [@books]; # reference a copy

You would then access elements of the array using something like

$authors->[$x]->{'books'}->[0]

which can be abbreviated

$authors->[$x]{books}[0]

or access the whole array as

@{$authors->[$x]{books}}

Your original attempt

$authors->[$x]->{'books'} = @books;

is exactly equivalent to

$authors->[$x]->{'books'} = scalar @books;

because the left operand of the = operator is a hash value, which is a scalar, so the right operand is evaluated in scalar context to provide something that can be assigned there.

P.S.

On rereading this answer I realized it may be confusing to say "a hash value is a scalar" because of the possible interpretation of "hash value" as meaning "the value of a hash variable" i.e. "the whole hash". What I mean when I write "hash value" is an item that is stored in a hash as a value (as opposed to a key).

Upvotes: 10

Related Questions