如何在Perl哈希表中存储多个值?
-
07-07-2019 - |
题
直到最近,我一直在使用相同的键将多个值存储到不同的哈希中,如下所示:
%boss = (
"Allan" => "George",
"Bob" => "George",
"George" => "lisa" );
%status = (
"Allan" => "Contractor",
"Bob" => "Part-time",
"George" => "Full-time" );
然后我可以引用 $ boss(" Bob")
和 $ status(" Bob")
但如果每个都有很多属性,这会变得笨拙密钥可以有,我不得不担心保持哈希同步。
有没有更好的方法在哈希中存储多个值?我可以将值存储为
"Bob" => "George:Part-time"
然后用拆分拆解字符串,但必须有更优雅的方式。
解决方案
这是标准方式,根据 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
其他提示
哈希哈希是你明确要求的。 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";
哈希可以包含其他哈希或数组。如果要按名称引用属性,请将它们存储为每个键的哈希值,否则将每个键存储为一个数组。
语法参考。
my %employees = (
"Allan" => { "Boss" => "George", "Status" => "Contractor" },
);
print $employees{"Allan"}{"Boss"}, "\n";
%chums =(" Allan" => {" Boss" =>" George"," Status" =>" Contractor"}, "鲍勃" => {"老板" => “彼得”,“状态”, => “兼职”});
效果很好但有更快的方式输入数据吗?
我在想像
这样的东西%chums =(qw,x)(Allan Boss George Status Contractor Bob Boss Peter Status兼职)
其中x =主键之后的辅助键的数量,在这种情况下x = 2,“Boss”。和“状态”
不隶属于 StackOverflow