views:

80

answers:

4

I am trying to figure out a way to initialize a hash without having to go through a loop. I was hoping to use slices for that, but it doesn't seem to produce the expected results.

Consider the following code:

#!/usr/bin/perl
use Data::Dumper;

my %hash = ();
$hash{currency_symbol} = 'BRL';
$hash{currency_name} = 'Real';
print Dumper(%hash);

This does work as expect and produce the following output:

$VAR1 = 'currency_symbol';
$VAR2 = 'BRL';
$VAR3 = 'currency_name';
$VAR4 = 'Real';

When I try to use slices as follows, it doesn't work:

#!/usr/bin/perl
use Data::Dumper;

my %hash = ();
my @fields = ('currency_symbol', 'currency_name');
my @array = ('BRL','Real');
@hash{@array} = @fields x @array;

The output is:

$VAR1 = 'currency_symbol';
$VAR2 = '22';
$VAR3 = 'currency_name';
$VAR4 = undef;

There is obviously something wrong.

So my question would be: what is the most elegant way to initialize a hash given two arrays (the keys and the values)?

A: 
    %hash = ('current_symbol' => 'BLR', 'currency_name' => 'Real'); 

or

my %hash = ();
my @fields = ('currency_symbol', 'currency_name');
my @array = ('BRL','Real');
@hash{@fields} = @array x @fields;
Michael Pakhantsov
Thank you for this textbook example on how to initialize a hash. However, this is not what I am looking for. I would like to see if it can be done with splices.
emx
+1  A: 

For the first one, try

my %hash = 
( "currency_symbol" => "BRL",
  "currency_name" => "Real"
);
print Dumper(\%hash);

The result will be:

$VAR1 = {
          'currency_symbol' => 'BRL',
          'currency_name' => 'Real'
        };
Paul Tomblin
Thank you for this textbook example on how to initialize a hash. However, this is not what I am looking for. I would like to see if it can be done with splices.
emx
Actually @emx, I was more concerned with showing you why your Data:Dumper output didn't look like a hash.
Paul Tomblin
I think you meant to vote me down rather than accept me, but I don't think I deserve either.
Paul Tomblin
Right. Actually this has indeed been bothering me - thank you for the clarification :)
emx
Not sure abut this vote/accept thing. New here!
emx
@emx, you're doing fine so far. Sorry about not understanding the gist of your question.
Paul Tomblin
+7  A: 
use strict;
use warnings;  # Must-haves

# ... Initialize your arrays

my @fields = ('currency_symbol', 'currency_name');
my @array = ('BRL','Real');

# ... Assign to your hash

my %hash;
@hash{@fields} = @array;
Zaid
Thanks - perfect!
emx
+5  A: 

So, what you want is to populate the hash using an array for the keys, and an array for the values. Then do the following:

#!/usr/bin/perl
use strict;
use warnings;

use Data::Dumper; 

my %hash; 

my @keys   = ("a","b"); 
my @values = ("1","2");

@hash{@keys} = @values;

print Dumper(\%hash);'

gives:

$VAR1 = {
          'a' => '1',
          'b' => '2'
        };
nicomen
Thanks - this is exactly what I was looking for. It's almost too simple.
emx