2016-03-03 24 views
0

更多細節:創建在Perl的子程序,將採取的哈希從散列的散列作爲參數,並從該散列打印出的其中一個值

第一哈希:錯誤消息的散列
第二散列:錯誤消息本身(ERROR_NAME)

其中包含3個關鍵值(的StatusCode,消息,則params)

我試圖創建將在ERROR_NAME並打印出消息的方法。 這是我在一分鐘代碼:

`our %error = (
       ERROR_1 => { 
            statusCode => 561. 
            message => "an unexpected error occurred at location X", 
            params => $param_1, 
          } 
       ERROR_2 => { 
            statusCode => 561. 
            message => "an unexpected error occurred at location Y", 
            params => $param_1, 
          } 
); 
` 

這可能嗎? 我試圖創建一個子程序,它會從哈希%錯誤中獲取一個錯誤並打印出它的消息。這可能嗎? 或者也許有更好的方法來做到這一點。

+0

簡短的回答:是的。但是,如果您向我們展示一個簡短的示例(perl代碼),說明您的結構如何,您將得到更詳細的答案。 – PerlDuck

+0

您應該發佈您遇到問題的代碼。請參閱[問]以獲取更多信息。 –

回答

1

一些例子來理解結構。這些都意味着相同(差異很小):

# just a hash 
%hash = ('a', 1, 'b', '2'); 
%hash = (a => 1, b => '2'); 
# ref to hash 
$hash_ref = \%hash; 
$hash_ref = { a => 1, b => 2 }; 

print $hash{ a }; #prints 1 
print $hash_ref->{ a }; #prints 1 

1和'2'是值。價值觀可能只是標量。參考SOMETHING也是標量。上面例子中的$ hash_ref。

在你的例子中,你說1st hash是列表。我認爲你的意思是陣列:

$list = [ $error1, $error2 ]; 

$error1 = { error_name => $description } 

$description = { status => 'status', message => 'msg', params => [ 1,2,'asdf'] } 

你知道一個子標量列表。如果你想哈希傳遞到子你只是通過參照本哈希

fn(\%hash); 

,並得到這個哈希在子:

sub fn { 
    my($hash) = @_; 
    print $hash->{ key_name }; 
} 

我想你只是一個錯誤的列表,每個都包含鍵:

$list_of_errors = [ 
    { status => 1, message => 'hello' }, 
    { status => 2, message => 'hello2' }, 
    { status => 1, message => 'hello3' }, 
] 

fn($list_of_errors); 

sub fn { 
    my($le) = @_; 

    print $le->[1]{ message }; #will print 'hello2' 
    # print $le->{ error_name }{ status }; #try this in case hash of hashes 
} 

要理解結構更好地嘗試使用Data :: Dump模塊;

use Data::Dump qw/ pp /; 
%hash = (a => 1); 
$hash = \%hash; 
$arr = [ 1, 2, 'a' ]; 
print pp $hash, \%hash, $arr; 

祝你好運。

CODE

our %error = (
    ERROR_1 => { 
     statusCode => 561, 
     message => "an unexpected error occurred at location X", 
     params => $param_1, 
    }, 
    ERROR_2 => { 
     statusCode => 561, 
     message => "an unexpected error occurred at location Y", 
     params => $param_1, 
    } 
); 

sub print_err { 
    my($err_name) = @_; 

    print $error{ $err_name }{ message } ."\n"; 
} 

print_err('ERROR_1'); 
print_err('ERROR_2'); 
+0

用代碼更新了問題。 @EugenKonkov –