0

更多细节:

第一个散列:错误消息的
散列第二个散列:错误消息本身(error_name)

其中包含 3 个键值(statusCode、message、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,
                          }
);
`

这可能吗?我正在尝试创建一个子例程,它将从哈希 %error 中获取错误并打印出它的消息。这可能吗?或者也许有更好的方法来做到这一点。

4

1 回答 1

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 在上面的例子中。

在您的示例中,您说第一个哈希是列表。我认为你的意思是数组:

$list = [ $error1, $error2 ];

$error1 = { error_name => $description }

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

您知道 sub 获取标量列表。如果你想将散列传递给 sub 你只需传递对这个散列的引用

fn( \%hash );

并在 sub 处获取此哈希:

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;

祝你好运。

代码

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' );
于 2016-03-03T21:57:16.750 回答