olala
olala

Reputation: 4456

Perl: assign array to hash values?

I was trying to initiate a hash that have 7 NAs as values.

This is what I have:

values %hash = ("NA") x 7;
print join("\t",values %hash),"\n";

I got this error:

Can't modify values in scalar assignment at line 22, near "7;"

Apparently, I can't do this with values of hash although I can assign array to hash keys

keys %hash = ["a","b","c","d","e","f","g"];

Why is it working for keys but not values for hash assignment?

Upvotes: 1

Views: 1858

Answers (2)

amon
amon

Reputation: 57640

From perldoc -f keys:

Used as an lvalue, "keys" allows you to increase the number of hash buckets allocated for the given hash. This can gain you a measure of efficiency if you know the hash is going to get big.

I.e. this method is not useful to set the keys, only to allocate space for a certain number of entries. When using a reference as the number, the result will probably be something ridiculously large that will eat most of your memory – not exactly recommended.

To initialize a hash with some values, you have to specify the required keys. But you can use a slice as an lvalue:

my %hash;
@hash{1..7} = ("NA") x 7;

Note: an lvalue is a value that can be used on the left side of an assignment.

Upvotes: 6

Zaid
Zaid

Reputation: 37146

A hash has two parts to it, keys and values. e.g.:

my %hash = ( a => 1, b => 2, c => 3 );

Here, the keys are 'a', 'b' and 'c'. The values are 1, 2 and 3.

If you look at what keys and values do, they (unsurprisingly) return the keys and values of the hash respectively.

They are not meant to set the values or keys of a hash, merely to retrieve.


Upvotes: 1

Related Questions