如何在Perl哈希表中存储多个值?

时间:2008-10-10 07:47:53

标签: perl hash multiple-value perl-data-structures

直到最近,我一直在使用相同的键将多个值存储到不同的哈希中,如下所示:

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

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

然后我可以引用$boss("Bob")$status("Bob")但是如果每个密钥都有很多属性,这会变得笨拙,我不得不担心保持哈希同步。

有没有更好的方法在哈希中存储多个值?我可以将值存储为

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

然后用拆分拆解字符串,但必须有更优雅的方式。

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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";

答案 2 :(得分:3)

哈希可以包含其他哈希或数组。如果要按名称引用属性,请将它们存储为每个键的哈希值,否则将每个键存储为一个数组。

reference for the syntax

答案 3 :(得分:2)

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

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

答案 4 :(得分:0)

%chums =(“Allan”=> {“Boss”=>“George”,“状态”=>“承包商”},            “Bob”=> {“Boss”=> “彼得”,“状态”=> “兼职”});

效果很好但有更快的方式输入数据吗?

我在想像

这样的东西

%chums =(qw,x)(Allan Boss George Status Contractor Bob Boss Peter Status兼职)

其中x =主键后的辅助键数,在这种情况下x = 2,“Boss”和“Status”