3

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!

1
  • 1
    The Data Structures Cookbook has a lot of good info on working with data structures. There are loads of examples of creating, storing and accessing data. perldoc.perl.org/perldsc.html
    – daotoad
    Commented Oct 4, 2009 at 6:20

4 Answers 4

12

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.

4
  • You can also access individual elements with $hash{fieldName}[$index]
    – friedo
    Commented Oct 3, 2009 at 23:20
  • 1
    @friedo - I think you mean $hash{fieldName}->[$index] Commented Oct 4, 2009 at 13:48
  • @joe, the -> is not needed. Check out the examples in perldsc.
    – daotoad
    Commented Oct 4, 2009 at 19:50
  • 1
    @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]"; Commented Oct 5, 2009 at 13:22
6

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)

0
5

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.

4

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}}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.