直到最近,我一直在使用相同的键将多个值存储到不同的哈希中,如下所示:
%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";