2008-10-10 90 views
24

直到最近,我一直在存儲多個值與相同的密鑰不同的散列如下:如何將多個值存儲在Perl哈希表中?

%boss = (
    "Allan" => "George", 
    "Bob" => "George", 
    "George" => "lisa"); 

%status = (
    "Allan" => "Contractor", 
    "Bob" => "Part-time", 
    "George" => "Full-time"); 

,然後我可以引用$boss("Bob")$status("Bob")但這變得笨拙,如果有大量的屬性每個鍵的可以有,我不得不擔心保持哈希同步。

有沒有更好的方法來存儲散列中的多個值?我可以將值存儲爲

 "Bob" => "George:Part-time" 

然後用split拆分字符串,但必須有更優雅的方式。

+1

這是Perl數據結構食譜爲什麼是這麼好的資源的一個很好的提示。 – dreftymac 2013-07-09 22:40:46

回答

26

這是標準方式,按照perldoc perldsc

~> more test.pl 
%chums = ("Allan" => {"Boss" => "George", "Status" => "Contractor"}, 
      "Bob" => {"Boss" => "Peter", "Status" => "Part-time"}); 

print $chums{"Allan"}{"Boss"}."\n"; 
print $chums{"Bob"}{"Boss"}."\n"; 
print $chums{"Bob"}{"Status"}."\n"; 
$chums{"Bob"}{"Wife"} = "Pam"; 
print $chums{"Bob"}{"Wife"}."\n"; 

~> perl test.pl 
George 
Peter 
Part-time 
Pam 
+0

看起來沒問題。我想我可以用$ chums {「Greg」} = {「Boss」=>「Lisa」,「Status」=>「Fired」}添加另一個好友,但我該如何爲Bob添加一個妻子?那會是$ chums {「Bob」} {「Wife」} =「Carol」? – paxdiablo 2008-10-10 08:11:18

+0

另外,爲什麼「 - >」。它似乎沒有這些功能。 – paxdiablo 2008-10-10 08:13:27

3

散列可以包含其他散列或數組。如果您想按名稱引用您的屬性,請將它們存儲爲每個鍵的散列值,否則將它們作爲每個鍵的數組存儲。

有一個reference for the syntax

2
my %employees = (
    "Allan" => { "Boss" => "George", "Status" => "Contractor" }, 
); 

print $employees{"Allan"}{"Boss"}, "\n"; 
23

哈希值是您明確要求的值。 Perl文檔中有一個教程式的文檔部分,它涵蓋了這個部分:Data Structure Cookbook但也許你應該考慮面向對象。這是面向對象編程教程的一個典型例子。

怎麼是這樣的:

#!/usr/bin/perl 
package Employee; 
use Moose; 
has 'name' => (is => 'rw', isa => 'Str'); 

# should really use a Status class 
has 'status' => (is => 'rw', isa => 'Str'); 

has 'superior' => (
    is  => 'rw', 
    isa  => 'Employee', 
    default => undef, 
); 

############### 
package main; 
use strict; 
use warnings; 

my %employees; # maybe use a class for this, too 

$employees{George} = Employee->new(
    name => 'George', 
    status => 'Boss', 
); 

$employees{Allan} = Employee->new(
    name  => 'Allan', 
    status => 'Contractor', 
    superior => $employees{George}, 
); 

print $employees{Allan}->superior->name, "\n"; 
0

%密友=( 「艾倫」=> { 「老大」=> 「喬治」, 「狀態」=> 「承包商」}, 「鮑勃」 => {「Boss」=>「Peter」,「Status」=>「兼職」});

工程很好,但有沒有更快的方式輸入數據?後

我想到的是像

%密友=(QW,X)(阿倫老闆喬治狀態承包商鮑勃老闆彼得狀態兼職)

其中x =輔助鍵的數量主鍵,在這種情況下x = 2,「老闆」和「狀態」