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拆解字符串,但一定有更优雅的方式。

4

5 回答 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
于 2008-10-10T08:00:41.083 回答
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";
于 2008-10-10T08:16:33.610 回答
4

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

有一个语法参考

于 2008-10-10T08:03:13.730 回答
2
my %employees = (
    "Allan" => { "Boss" => "George", "Status" => "Contractor" },
);

print $employees{"Allan"}{"Boss"}, "\n";
于 2008-10-10T08:05:32.960 回答
0

%chums = ( "Allan" => {"Boss" => "George", "Status" => "Contractor"}, "Bob" => {"Boss" => "Peter", "Status" => "兼职”} );

效果很好,但有没有更快的方法来输入数据?

我在想类似的东西

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

其中 x = 主键之后的辅助键的数量,在这种情况下 x = 2,“老板”和“状态”

于 2013-12-22T21:34:55.757 回答