Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 213
Dave Avatar asked Aug 15 '11 16:08

Dave


People also ask

Can a Key have multiple values Perl?

Each key can only have one value.

What is @$ in Perl?

@$ 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} .

How do I save a key value pair in Perl?

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

What does keys do in Perl?

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.


1 Answers

You can write this:

my %hash;
$hash{$_} = $valA for qw(a b c);
$hash{$_} = $valB for qw(d e f);
like image 169
Robert Avatar answered Nov 17 '22 00:11

Robert