Pass array by value to hash value in Perl?

I am new to Perl and testing several things. One thing I noticed is if someone wants to pass an array as the value of a hash key, one way to do this is to pass it by reference. Properly

$hash_map{key} = \@arr 

Is there a way to pass an array by value directly? Thanks

+1
source share
2 answers

The hash maps strings (keys) to scalar values. The value in the hash can only be a scalar.

An array is not (by definition!) A scalar. The best way to get the scalar value that this array represents is to take a reference to this array. And this is what your code does. Here's how you should do it.

There are other ways to create a scalar value to represent an array. For example, you can use join() to create a string from array elements. But that would be very fragile, since you would need to find a separator character that does not appear in any of the elements.

It’s much better to just take the link, as you already do.

Update: To clarify, there are three ways to do this with links.

  • $hash{key} = \@array - refers to an array and stores the link in $hash{key} .
  • $hash{key} = [ @array ] - expands the array into a list, creates a new array using this list as elements, and returns a link to this new array (effectively copying the array).
  • @{$hash{key}} = @array - this also takes a copy of the array and saves a link to the copy.
+4
source

The following works are just fine for me according to perl 5.10 and 5.14:

 use strict; use Data::Dumper; my @array= qw(foo 42 bar); my %hash; @{ $hash{key} } = @array; $hash{key} = [ @array ]; #same as above line print Dumper(\%hash,$hash{key}[1]); 

(your order may vary):

 $VAR1 = { 'key' => [ 'foo', '42', 'bar' ] }; $VAR2 = '42'; 

I prefer the syntax @{ $hash{key} } because you can click / place it, i.e.

 push @{ $hash{key} }, "value"; 

which is surprisingly convenient (for me anyway)
In addition, with this syntax, you copy the array, and not just add a reference to it, that is, you can change the original array without affecting the hash

0
source

Source: https://habr.com/ru/post/1271211/


All Articles