如何在perl中合并hash in hash?

时间:2013-07-19 06:52:38

标签: perl hash

my %book = (
'name' => 'abc',
'author' => 'monk',
'isbn' => '123-890',
'issn' => '@issn',           
);

my %chapter = (
'title' => 'xyz',
'page' => '90',             
);

如何通过引用将%book合并到%章节中,这样当我写“$ chapter {name}”时,它应该打印'abc'?

2 个答案:

答案 0 :(得分:3)

  1. 您可以将%book的键/值复制到%chapter

    @chapter{keys %book} = values %book;
    

    或类似

    %chapter = (%chapter, %book);
    

    现在您可以say $chapter{name},但%book中的更改未反映在%chapter中。

  2. 您可以参考%book来参考:

    $chapter{book} = \%book;
    

    现在你可以say $chapter{book}{name},并且可以反映出变化。

  3. 要拥有一个允许您说出$chapter{name}且确实反映更改的界面,必须使用一些高级技术(这对tie magic而言相当微不足道),但不要去那里除非你真的必须。

答案 1 :(得分:1)

您可以编写子程序来检查密钥的哈希列表。该计划表明:

use strict;
use warnings;

my %book = (
  name   => 'abc',
  author => 'monk',
  isbn   => '123-890',
  issn   => '@issn',           
);

my %chapter = (
  title => 'xyz',
  page  => '90',             
);

for my $key (qw/ name title bogus / ) {
  print '>> ', access_hash($key, \%book, \%chapter), "\n";
}

sub access_hash {
  my $key = shift;
  for my $hash (@_) {
    return $hash->{$key} if exists $hash->{$key};
  }
  undef;
}

<强>输出

Use of uninitialized value in print at E:\Perl\source\ht.pl line 17.
>> abc
>> xyz
>>