Create a hash in Perl

I have an initial question:

I have @key_table and many @values_tables. I want to create @table links to hashes, so there is one table, each element points to a hash with keys and values ​​from these two tables presented at the beginning.

Can anyone help me?

For instance:

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

and I want the two-element table to point to:

 %hash1 = (Kate=>1, Peter=>2, John=>3); %hash2 = (Kate=>a, Peter=>b, John=>c); 
+4
source share
4 answers

If you just want to create two hashes, this is very simple:

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

This uses hash slices .

However, it is usually a mistake to make a bunch of new variables with numbers stuck in the end. If you want this information to be combined into one structure, you can create nested hashes with links.

+6
source

Using a hash slice is the most common way to populate the hash with keys / values,

  @hash1{@keys} = @value1; @hash2{@keys} = @value2; 

but this can be done in a different (less efficient) way using ie. map

 my %hash1 = map { $keys[$_] => $value1[$_] } 0 .. $#keys; my %hash2 = map { $keys[$_] => $value2[$_] } 0 .. $#keys; 

or even foreach

 $hash1{ $keys[$_] } = $value1[$_] for 0 .. $#keys; $hash2{ $keys[$_] } = $value2[$_] for 0 .. $#keys; 
+2
source

This is an example:

 use strict; use warnings; use Data::Dump; #Example data my @key_table = qw/Kate Peter John/; my @values_tables = ( [qw/1 2 3/], [qw/abc/] ); my @table; for my $vt(@values_tables) { my %temph; @temph{ @key_table } = @$vt; push @table, \%temph; } dd(@table); #<--- prints: #( # { John => 3, Kate => 1, Peter => 2 }, # { John => "c", Kate => "a", Peter => "b" }, #) 
+1
source

This will be done:

  use Data::Dumper; use strict; my @keys = ("Kate", "Peter", "John"); my @value1 = (1, 2, 3); my @value2 = ("a", "b", "c"); my (%hash1,%hash2); for my $i (0 .. $#keys){ $hash1{$keys[$i]}=$value1[$i]; $hash2{$keys[$i]}=$value2[$i]; } print Dumper(\%hash1); print Dumper(\%hash2); 

This is the conclusion:

 $VAR1 = { 'John' => 3, 'Kate' => 1, 'Peter' => 2 }; $VAR1 = { 'John' => 'c', 'Kate' => 'a', 'Peter' => 'b' }; 
-1
source

Source: https://habr.com/ru/post/1483417/


All Articles