1

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?

5
  • So the big question is: Why do you want a hash with 7 NAs in it? Commented Mar 4, 2014 at 19:55
  • @LenJaffe : OP wanted a hash with 7 values in it. Commented Mar 4, 2014 at 19:56
  • Yes. I saw that. But Why a hash? OP created a hash using list assignment. I'm trying to get a level deeper to find out what OP is actually trying to accomplish. Commented Mar 4, 2014 at 20:00
  • i need to process the hash later... to use the keys in the hash Commented Mar 4, 2014 at 20:02
  • I got around it with the answers from this post: stackoverflow.com/questions/3556052/… Commented Mar 4, 2014 at 20:02

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.