当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在Perl哈希表中存储多个值?》经验,为你挑选了2个好方法。

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

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

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

然后我可以参考$boss("Bob"),$status("Bob")但如果每个键都有很多属性,这就变得笨拙,我不得不担心保持哈希同步.

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

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

然后拆分拆分弦,但必须有一个更优雅的方式.



1> Vinko Vrsalo..:

这是标准方式,根据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


TIMTOWDI :),您可以在没有它们的情况下使用它,是的,您添加妻子的方式是正确的

2> tsee..:

哈希的哈希是你明确要求的.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";


这样可以在将来增强它.
推荐阅读
LEEstarmmmmm
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有