你的問題是,你的map
表達式返回
undef
在@array
第一元素的假值。
然後將它用作散列鍵,將其字符串化爲空字符串。
(在評論鮑羅廷指出,這種解釋是不正確。事實上空字符串來自於從exists
返回時,關鍵是「1」的假值)
你可能會得到更好的主意如果你a)開啓了strict
和warnings
和b)使用Data::Dumper
在你創建它之後顯示哈希值。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use Data::Dumper;
my @array = (1 .. 5);
my %hash = (2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five');
my %hash1 = map { $_=>$hash{$_} if(exists $hash{$_}) } @array;
say Dumper \%hash1;
這表明你結束了這樣的哈希:
$ ./hash
Odd number of elements in hash assignment at ./hash line 12.
$VAR1 = {
'' => 2,
'three' => 4,
'five' => undef,
'two' => 3,
'four' => 5
};
您正在生成具有奇數個元素的列表。這並不能令人滿意。
當你構建一個散列時,你需要確保你有一個偶數個元素。因此,當您使用map
時,您需要爲每次迭代返回零個或兩個元素。所以你需要這樣的東西:
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use Data::Dumper;
my @array = (1 .. 5);
my %hash = (2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five');
my %hash1 = map { exists $hash{$_} ? ($_ => $hash{$_}) :() } @array;
say Dumper \%hash1;
請注意,我們顯式返回一個空列表,當在第一個哈希中找不到鍵。
$ ./hash2
$VAR1 = {
'4' => 'four',
'3' => 'three',
'2' => 'two',
'5' => 'five'
};
非常快,非常準確的。 – Jassi 2012-07-13 10:02:48
你對'undef'被串接爲空字符串的解釋是錯誤的*。您看到的空字符串是不存在的鍵的存在$ hash {$ _}的值。如果沒有使用未初始化值的警告噪聲,undef不會被轉換爲空字符串。 – Borodin 2012-07-13 10:26:43
謝謝。糾正。 – 2012-07-13 14:00:40