maciek maciek - 1 month ago 5
Perl Question

Create a hash in Perl

I have a beginner question:

I have an @key_table and many @values_tables.
I want to create a @table of references to hashes, so there is one table, each element points to hash with keys&values from those 2 tables presented at the beginning.

Could anyone help me?



For example:

@keys = (Kate, Peter, John);
@value1 = (1, 2, 3);
@value2 = (a, b, c);


and I want a two-element table that point to:

%hash1 = (Kate=>1, Peter=>2, John=>3);
%hash2 = (Kate=>a, Peter=>b, John=>c);

Answer

If you just want to create two hashes, it's really easy:

my ( %hash1, %hash2 );
@hash1{ @keys } = @value1;
@hash2{ @keys } = @value2;

This takes advantage of hash slices.

However, it's usually a mistake to make a bunch of new variables with numbers stuck on the end. If you want this information all together in one structure, you can create nested hashes with references.