tags:

views:

137

answers:

4

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 way of assigning an existing one. I basically want to go:

$hash{fieldName} = @myArray;

Only that obviously doesn't work! Help appreciated!

+11  A: 

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.

Lukáš Lalinský
You can also access individual elements with `$hash{fieldName}[$index]`
friedo
@friedo - I think you mean `$hash{fieldName}->[$index]`
Joe Casadonte
@joe, the `->` is not needed. Check out the examples in perldsc.
daotoad
@daotoad - you're right, of course. However, I would never consider using that notation, as it confuses things (you're accessing an element of an array ref as if it were an array, which while syntactically correct could also be confusing to someone with less Perl knowledge). Given: `my(@foo) = (1..3); my(%bar) = (a => 1, b => 2, c => 3); $bar{d} = \@foo;` then `print "D: $bar{d}->[1]";` and `print "D: $bar{d}[1]";` both print "D: 2". But this: `my($baz) = $bar{d}; print "$baz[1]";` produces an error, while this is OK: `print "$baz->[1]";`
Joe Casadonte
+4  A: 

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}}
Tom
+6  A: 

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)

V_D_R
Sinan - thanks for editing!
V_D_R
+5  A: 

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.

Sinan Ünür