位元詩人 [Raku] 程式設計教學:雜湊表 (Hash Table)

Facebook Twitter LinkedIn LINE Skype EverNote GMail Yahoo Email

雜湊 (hash) 是以 (鍵, 值) 對 (key-value pair) 為單位的非線性容器,相當實用的容器。

建立雜湊

Perl 6 內建建立雜湊的語法,實例如下:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. my %hash = one => "eins", two => "zwei", three => "drei";
  2.  
  3. %hash<two> eq "zwei" or die "Wrong value";

也可以先建立空雜湊後,再逐一填入鍵/值對,如下例:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. my %hash;
  2.  
  3. %hash<one> = "eins";
  4. %hash<two> = "zwei";
  5. %hash<three> = "drei";
  6.  
  7. %hash<two> eq "zwei" or die "Wrong value";

走訪雜湊

使用 for 迴圈搭配 keys 方法可走訪雜湊,得到鍵,如下例:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. my %hash = one => "eins", two => "zwei", three => "drei";
  2.  
  3. for %hash.keys -> $k {
  4.     %hash{$k}.say;
  5. }

也可以走訪其值,如下例:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. my %hash = one => "eins", two => "zwei", three => "drei";
  2.  
  3. for %hash.values -> $v {
  4.     $v.say;
  5. }

要注意的是,雜湊取索引是單向的,僅能從鍵推得值,無法從值回推鍵。

使用 for 迴圈搭配 kv 方法走訪雜湊,可得到鍵/值對,如下例:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. my %hash = one => "eins", two => "zwei", three => "drei";
  2.  
  3. for %hash.kv -> $k, $v {
  4.     "{$k}: {$v}".say;
  5. }

如果需要特定的順序,可對鍵進行排序,如下例:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. my %hash = one => "eins", two => "zwei", three => "drei";
  2.  
  3. for %hash.keys.sort({ $^a cmp $^b }) -> $k {
  4.     %hash{$k}.say;
  5. }

我們將於後續文章介紹排序。

刪除鍵值對

透過 :delete 可移除鍵/值對,見下例:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. my %hash = one => "eins", two => "zwei", three => "drei";
  2.  
  3. %hash.keys.elems == 3 or die "Wrong count";
  4.  
  5. # Delete one key-value pair.
  6. %hash<three>:delete;
  7.  
  8. %hash.keys.elems == 2 or die "Wrong count";

關於作者

位元詩人 (ByteBard) 是資訊領域碩士,喜歡用開源技術來解決各式各樣的問題。這類技術跨平台、重用性高、技術生命長。

除了開源技術以外,位元詩人喜歡日本料理和黑咖啡,會一些日文,有時會自助旅行。