Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a hash in Perl

Tags:

hash

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);
like image 257
maciek Avatar asked Feb 17 '23 09:02

maciek


1 Answers

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.

like image 162
friedo Avatar answered Feb 19 '23 00:02

friedo