开发者

How can I use an existing array as a value in a hash in Perl?

I have an existing array I wish to add as a value in a hash. I know you can use arrays as values but can see no w开发者_如何转开发ay of assigning an existing one. I basically want to go:

$hash{fieldName} = @myArray;

Only that obviously doesn't work! Help appreciated!


You can store only scalar values in hashes/arrays. You need to use:

$hash{fieldName} = \@myArray;

to store it, and:

my @myOtherArray = @{$hash{fieldName}};

to get it back. It's working around the scalar requirement by using a reference to the array.


And since nobody mentioned it, what your code did was as follows:

  • since you were assigning to an element of the hash, the assignment was in scalar context

  • in scalar context, the value of the array becomes the size of the array

  • so, the value of $hash{fieldName} became equal to size of the array (scalar @myarray)


While the correct answer is indeed to store a reference, there are times where the distinctions between \@myArray, [ @myArray ] (shallow copy) and dclone (deep copy) matter.

If you have, $hash{fieldName} = \@myArray, then $hash{fieldName}->[2] will modify the third element of @myArray. If @myArray itself does not contain any references, then storing a shallow copy will help you avoid that behavior.


You can store a reference to the array using the backslash operator '\' eg

$hash{fieldName} = \@myArray

You can then use the following to access it:

@{$hash{fieldName}}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜