2010-08-24 122 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

相關問題