Reputation: 811
I am extracting data and the resulting hash can be one of two examples:
$VAR1 = {
'calculated_at' => '2015-09-01T03:27:11.528Z',
'result' => {
'previous' => 0,
'now' => 71
}
};
$VAR1 = {
'calculated_at' => '2015-09-01T03:27:11.624Z',
'result' => 342
};
If example1 , the value should be 71, else it should be 342.
I have tried:
if (exists $jhash{result}{now}) { print "Test\n";}
But that breaks on the second example:
Can't use string ("341") as a HASH ref while "strict refs" in use
What is the proper way to do this?
Upvotes: 1
Views: 68
Reputation: 6602
Use ref
to see if result is a reference. perldoc ref
#!/usr/bin/env perl
use warnings;
use strict;
my $results_data = [
{
'calculated_at' => '2015-09-01T03:27:11.528Z',
'result' => {
'previous' => 0,
'now' => 71
}
},
{
'calculated_at' => '2015-09-01T03:27:11.624Z',
'result' => 342
},
];
for my $data (@$results_data) {
my $result = ref $data->{result} ? $data->{result}->{now} : $data->{result};
print "Result is $result\n";
}
Output:
Result is 71
Result is 342
Upvotes: 4