2013-07-19 72 views
0
my %book = (
'name' => 'abc', 
'author' => 'monk', 
'isbn' => '123-890', 
'issn' => '@issn',   
); 

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

如何通過引用將%book內的%book合併到%chapter中,以便當我編寫「$ chapter {name}」時,它應該打印'abc'?如何將散列內部的散列合併到perl中?

+1

無人盯防交叉後http://perlmonks.org/?node_id=1045267 – daxim

回答

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},變化也得到體現。

爲了有一個接口,使您可以說$chapter{name},並且確實反映了變化,一些先進的技術,就必須使用(這是tie magic相當微不足道的),但不要去那裏,除非你真的必須。

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 
>>