如何在没有循环的情况下初始化散列中的值?

时间:2010-08-24 11:45:33

标签: arrays perl hash slice

我试图找出一种初始化哈希的方法,而不必经历一个循环。我本来希望使用切片,但它似乎没有产生预期的结果。

请考虑以下代码:

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

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

这确实按预期工作并产生以下输出:

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

当我尝试按如下方式使用切片时,它不起作用:

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

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

输出结果为:

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

显然有些不对劲。

所以我的问题是:给定两个数组(键和值)初始化哈希的最优雅方法是什么?

4 个答案:

答案 0 :(得分:23)

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;

答案 1 :(得分:13)

所以,你想要的是使用数组为键填充哈希值,以及值的数组。然后执行以下操作:

#!/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);'

给出:

$VAR1 = {
          'a' => '1',
          'b' => '2'
        };

答案 2 :(得分:6)

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

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

答案 3 :(得分:3)

对于第一个,请尝试

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

结果将是:

$VAR1 = {
          'currency_symbol' => 'BRL',
          'currency_name' => 'Real'
        };