雜湊 (hash) 是以 (鍵, 值) 對 (key-value pair) 為單位的非線性容器,相當實用的容器。
建立雜湊
Perl 6 內建建立雜湊的語法,實例如下:
my %hash = one => "eins", two => "zwei", three => "drei";
%hash<two> eq "zwei" or die "Wrong value";
也可以先建立空雜湊後,再逐一填入鍵/值對,如下例:
my %hash;
%hash<one> = "eins";
%hash<two> = "zwei";
%hash<three> = "drei";
%hash<two> eq "zwei" or die "Wrong value";
走訪雜湊
使用 for
迴圈搭配 keys
方法可走訪雜湊,得到鍵,如下例:
my %hash = one => "eins", two => "zwei", three => "drei";
for %hash.keys -> $k {
%hash{$k}.say;
}
也可以走訪其值,如下例:
my %hash = one => "eins", two => "zwei", three => "drei";
for %hash.values -> $v {
$v.say;
}
要注意的是,雜湊取索引是單向的,僅能從鍵推得值,無法從值回推鍵。
使用 for
迴圈搭配 kv
方法走訪雜湊,可得到鍵/值對,如下例:
my %hash = one => "eins", two => "zwei", three => "drei";
for %hash.kv -> $k, $v {
"{$k}: {$v}".say;
}
如果需要特定的順序,可對鍵進行排序,如下例:
my %hash = one => "eins", two => "zwei", three => "drei";
for %hash.keys.sort({ $^a cmp $^b }) -> $k {
%hash{$k}.say;
}
我們將於後續文章介紹排序。
刪除鍵值對
透過 :delete
可移除鍵/值對,見下例:
my %hash = one => "eins", two => "zwei", three => "drei";
%hash.keys.elems == 3 or die "Wrong count";
# Delete one key-value pair.
%hash<three>:delete;
%hash.keys.elems == 2 or die "Wrong count";