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

24

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

%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
5个回答

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

看起来还不错。我想我可以添加另一个朋友,使用 $chums{"Greg"} = {"Boss" => "Lisa", "Status" => "Fired"},但是如何给Bob添加妻子呢?这应该是 $chums{"Bob"}{"Wife"} = "Carol" 吗? - paxdiablo
还有,为什么要用“->”?似乎没有这些也能正常运行。 - paxdiablo
2
TIMTOWDI :), 你可以不用它们,是的,你添加妻子的方式是正确的。 - Vinko Vrsalovic
这是一个关于 perldsc 价值的重要提醒。PHP、Python、Ruby 和 Perl 程序员都应该阅读此文。 - dreftymac

23

哈希的哈希是您明确要求的内容。Perl文档的一部分有一个教程样式的文档,涵盖了这个问题:数据结构食谱 ,但也许您应该考虑使用面向对象编程。这是面向对象编程教程的典型示例。

您觉得这个怎么样:

#!/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
这样做的好处是将来可以进行增强。 - Brad Gilbert

4

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

有一个语法参考可供使用。


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

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

0

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

这段代码很好用,但是有没有更快的方法来输入数据呢?

我在想像下面这样的方式:

%chums = (qw, x)( Allan Boss George Status Contractor Bob Boss Peter Status Part-time)

其中x表示主键后面的次要键数量,在这个例子中x=2,即“Boss”和“Status”。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接