Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize values in a hash without a loop?

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

like image 692
emx Avatar asked Aug 24 '10 11:08

emx


People also ask

How do I initialize a hash in Perl?

There are two ways to initialize a hash variable. One is using => which is called the fat arrow or fat comma. The second one is to put the key/value pairs in double quotes(“”) separated by a comma(,). Using fat commas provide an alternative as you can leave double quotes around the key.

How do you declare hash?

declare hash h; h = _new_ hash( ); A constructor is a method that you can use to instantiate a hash object and initialize the hash object data. For example, in the following line of code, the DECLARE statement declares and instantiates a hash object and assigns it to the object reference H.

Can a hash have multiple values?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

How do I create an empty hash in Perl?

You need to use the \ operator to take a reference to a plural data type (array or hash) before you can store it into a single slot of either. But in the example code given, if referenced, each would be the same hash.


1 Answers

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;
like image 133
Zaid Avatar answered Sep 21 '22 19:09

Zaid