Is there a simple syntax for declaring multiple keys with a single value in perl?

Is there an easy way to declare a hash with multiple keys that all point to the same value in perl?

Here is something similar to what I'm looking for (I really don't know if this works or not):

my $hash = { a, b, c => $valA, d, e, f => $valB }; 

such that ....

 print $hash->{a}; #prints $valA print $hash->{b}; #prints $valA print $hash->{c}; #prints $valA print $hash->{d}; #prints $valB print $hash->{e}; #prints $valB print $hash->{f}; #prints $valB 
+7
source share
7 answers

You can write this:

 my %hash; $hash{$_} = $valA for qw(abc); $hash{$_} = $valB for qw(def); 
+16
source

No, there is no simple syntax for this. (In fact, => documented as an alias for,, the only formal effect of which is that it allows the left of it even in strict mode).

The best you could do without defining your own submasters might be something like

 @hash{qw(abc)} = ($valA) x 3 ; @hash(qw(def)} = ($valB) x 3 ; 
+11
source

I like to use a hash fragment on the one hand and a list replication operator on the other. I use the scalar value of the key array to determine the number of replicated values:

  @hash{ @keys } = ($value) x @keys; 
+8
source

There is no built-in syntax, but you can always write your own:

 my $value = sub {map {$_ => $_[1]} @{$_[0]}}; my $hash = { [qw(abc)]->$value('valA'), [qw(def)]->$value('valB'), }; say join ', ' => map "$_: $$hash{$_}", sort keys %$hash; # a: valA, b: valA, c: valA, d: valB, e: valB, f: valB 

If you are going to do this a lot, you may need the Hash::Util hv_store , which allows you to load multiple keys with exactly the same memory location.

+6
source

You can use hash fragment assignment:

 my $hash = {}; @$hash{a,b,c} = ($valA) x 3; @$hash{d,e,f} = ($valB) x 3; 
+4
source

Assignment can also be performed using statements, for example, with map . Here the map will be expanded into two lists.

 my $hash = { ( map { $_ => $valA } ('a' .. 'c') ), ( map { $_ => $valB } ('d' .. 'f') ), }; 
+2
source

Yes, as Henning Maholm noted, there is no direct label, since => is an alias for,. I think the closest to the shortcut:

 foreach('a','b','c') { $hash->{$_}=$valA; } foreach('d','e','f') { $hash->{$_}=$valB; } 
+1
source