0

Below is the code

my $results = $session->array_of_hash_for_cursor("check_if_receipts_exist", 0, @params);
next if( scalar @{$results} <= 0 );
$logger->info("Retrieved number of records: ".scalar @$results);
foreach my $row( sort { $results->{$b}->{epoch_received_date} cmp $results->{$a}->{epoch_received_date} } keys %{$results} )
      {
       //logic
      }

'check_if_receipts_exists' is a SQL query which returns some results. Which I try to execute this, I am getting the following error, Bad index while coercing array into hash

I am new to Perl. Can someone please point out the mistake I am making?

1
  • Where is $session coming from? Commented Jan 13, 2012 at 17:31

1 Answer 1

3

Is $results a hash reference or an array reference?

In some places you are using it like an array reference:

scalar @{$results}

and in other places you are using it like a hash reference:

$results->{$b}->{...}
keys %{$results}

It can't be both (at least not without some heavy overload magic).

If I can infer from the name of the function that sets $results, it should be a reference to a list of hash references, then a few tweaks will set it right:

  1. Using @{$results} is correct; this expression is "an array of hash references"
  2. The last argument to sort should be a list, but the correct list to pass is @{$results}, not keys %{$results}.
  3. Then the parameters $a and $b inside the sort function will be members of @{$results}, that is, they will be hash references. So the comparison to make is

    $a->{epoch_received_date} cmp $b->{epoch_retrieve_data}

and not

    $results->{$a}->{...} cmp $results->{$b}->{...}

All together:

my $results = $session->array_of_hash_for_cursor(
   "check_if_receipts_exist", 0, @params);
next if !@$results;
$logger->info("Retrieved number of records: ".@$results);
for my $row (
    sort {
        $b->{epoch_received_date}
          cmp
        $a->{epoch_received_date}
    } @$results
) {
   # logic
}
Sign up to request clarification or add additional context in comments.

5 Comments

After making the above changes, I am getting the following error, Type of arg 1 to keys must be hash (not array dereference) at ...
@carkct - Read the suggestions again. I doubt there is any need to use keys. I'm guessing you should be using sort {...} @{$results}.
And keep your chin up. This stuff is complicated and confusing, but once you get the hang of it, it is very powerful and expressive.
I tried using foreach my $row( sort { {$b}->{epoch_received_date} cmp {$a}->{epoch_received_date} } @{$results} ) and it worked. Thanks.
@ikegami - I think there is an error in summary code (next if @$results seems reverse logic to OP's code)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.