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

萝らか妹 提交于 2019-12-03 01:46:22
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;

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'
        };
    %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;

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'
        };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!