maciek
maciek

Reputation: 2107

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);

Upvotes: 4

Views: 180

Answers (4)

mpapec
mpapec

Reputation: 50637

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

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

but it could be done in other (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;

Upvotes: 2

isJustMe
isJustMe

Reputation: 5470

This will do it:

   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 output:

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

Upvotes: -1

Miguel Prz
Miguel Prz

Reputation: 13792

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/a b c/]
);

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" },
#)

Upvotes: 1

friedo
friedo

Reputation: 66937

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.

Upvotes: 6

Related Questions