【问题标题】:How can I store multiple values in a Perl hash table?如何在 Perl 哈希表中存储多个值?
【发布时间】:2010-09-16 11:15:03
【问题描述】:

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

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

【问题讨论】:

  • 这很好地提醒了我们为什么 Perl 数据结构说明书是一个很好的资源。

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


【解决方案1】:

这是标准方式,根据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" 吗?
  • 另外,为什么是“->”。它似乎没有这些功能。
  • TIMTOWDI :),你可以不使用它,是的,你添加妻子的方式是正确的
  • 这很好地提醒了 perldsc 的价值。这应该是 PHP、Python、Ruby 和 Perl 程序员的必读内容。
【解决方案2】:

散列的散列是您明确要求的。 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";

【讨论】:

  • 这样的好处是以后可以增强。
【解决方案3】:

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

有一个reference for the syntax

【讨论】:

    【解决方案4】:
    my %employees = (
        "Allan" => { "Boss" => "George", "Status" => "Contractor" },
    );
    
    print $employees{"Allan"}{"Boss"}, "\n";
    

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 2012-02-01
        • 1970-01-01
        • 2016-06-16
        • 1970-01-01
        • 2014-07-17
        • 2013-10-09
        • 2017-10-18
        • 2018-04-17
        • 2010-09-20
        相关资源
        最近更新 更多