More details:
1st hash: hash of error messages
2nd hash: error message itself (error_name)
which contains 3 key values (statusCode, message, params)
I am trying to create a method that will take in error_name and print out the message. This is the code I have at the minute:
`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,
}
);
`
Is this possible? I'm trying to create a subroutine that will take an error from the hash %error and print out its message. Is this possible? Or maybe there is a better way of doing it.
Some examples to understand structures. These all mean same (with small difference):
# 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 and '2' are values. Values maybe only scalars. Reference to SOMETHING is also scalar. $hash_ref in the example above.
In your example you say 1st hash is list. I think you mean array:
$list = [ $error1, $error2 ];
$error1 = { error_name => $description }
$description = { status => 'status', message => 'msg', params => [ 1,2,'asdf'] }
You know that a sub get list of scalars. If you want to pass hash into sub you just pass reference to this hash
fn( \%hash );
and get this hash at sub:
sub fn {
my( $hash ) = @_;
print $hash->{ key_name };
}
I suppose you have just a list of errors, each of them contain keys:
$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
}
To understand structures better try to use Data::Dump module;
use Data::Dump qw/ pp /;
%hash = ( a => 1 );
$hash = \%hash;
$arr = [ 1, 2, 'a' ];
print pp $hash, \%hash, $arr;
Good luck.
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' );