Is there a simple way to declare a hash with multiple keys which all point to the same value in perl?
Here is something similar to what I'm looking for (I don't actually 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
Each key can only have one value.
@$ in the context above is not a variable. It's a dereference. $tp is a reference to an array. @$tp says "dereference and give me the values", it could also be written as @{$tp} .
A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..
keys() function in Perl returns all the keys of the HASH as a list. Order of elements in the List need not to be same always, but, it matches to the order returned by values and each function. Return: For scalar context, it returns the number of keys in the hash whereas for List context it returns a list of keys.
You can write this:
my %hash;
$hash{$_} = $valA for qw(a b c);
$hash{$_} = $valB for qw(d e f);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With