3

How can I merge two arrays together as an associative manner; one array having the key column names, and the other the values?

I have tried to push one array upon the other, put only appends them as a list, does not associate them together. Any help would be greatly appreciated it. Thanks!

my @var1 = {'COL1', 'COL2', 'COL3'};
my @var2 = {  '1' ,  '2'  , '3'   };

...

new array %var3 = {'COL1' => '1', 'COL2' => '2', 'COL3' => '3'} 
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196

2 Answers2

3

With hash slices:

my %var3;
@var3{ @var1 } = @var2;
Jim Davis
  • 5,241
  • 1
  • 26
  • 22
  • @LuisBerumen If the above answer solves your problem you should accept the answer and if there is any additional information or an alternative solution then you can share that with fellow members. – Rahul Sharma Dec 22 '14 at 22:02
3

First some comments. Arrays use simple parentheses ( and ).

And you can construct the hash with a hash slice:

my @keys = ('COL1', 'COL2', 'COL3');
my @values = ( '1' , '2' , '3' );

my %hash ;
@hash{@keys} = @values ;

This gives the desired hash you wanted.

Borodin
  • 126,100
  • 9
  • 70
  • 144
dgw
  • 13,418
  • 11
  • 56
  • 54