2008-10-10 54 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,“老板”和“状态”