2010-08-24 52 views
17

我想找出一种方法来初始化一个散列,而不必经过一个循环。我希望为此使用切片,但似乎没有产生预期的结果。如何在没有循环的情况下初始化散列值?

考虑下面的代码:

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

显然有些问题。

所以我的问题是:什么是最优雅的方式来初始化散列给出两个数组(键和值)?

回答

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; 
+0

谢谢 - 完美! – emx 2010-08-24 12:05:46

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; 
+0

感谢您对如何初始化一个哈希这本教科书的例子。但是,这不是我正在寻找的。我想看看它是否可以通过拼接完成。 – emx 2010-08-24 11:54:46

+1

,但对于第一个谷歌结果,这是一个非常非常有帮助的复习/语法确认 – lol 2014-09-13 05:50:23

3

这是第一个,尝试

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

结果将是:

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

感谢您的教科书示例如何初始化散列。但是,这不是我正在寻找的。我想看看它是否可以通过拼接完成。 – emx 2010-08-24 11:55:07

+0

其实@emx,我更关心的是向你展示为什么你的Data:Dumper输出看起来不像一个哈希。 – 2010-08-24 12:09:24

+0

我想你打算给我投票而不是接受我,但我不认为我配得上。 – 2010-08-24 12:10:42

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' 
     }; 
+0

谢谢 - 这正是我一直在寻找的。这几乎太简单了。 – emx 2010-08-24 11:58:26

相关问题