perl@1983 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, Below is from perlfaq4: Question is the thing used in push is array of hashes or hash of array? How do we recognize such structure? Is there any thumb rule?
while (($key, $value) = each %by_key) { push @{$key_list_by_value{$value}}, $key; }
Thanks in advance.

Replies are listed 'Best First'.
Re: Array of Hashes or Hash of Arrays
by jethro (Monsignor) on May 10, 2012 at 11:12 UTC

    How would you get at a value from an Array of Hashes? You would first have to specify one of the hashes in the array and then the value in that particular hash. So, first an array access, then a hash access, right? A Hash of Arrays would be the other way round, first a hash access, then an array access.

    Now as in any computer language I know expressions are evaluated from inner to outer braces, for example 2+5 would be the first do be evaluated in (3+(7*(2+5)+4)). So look at your expression, what is the innermost expression, an array or hash access? What is the outer expression, array or hash access? Once you know that you know what structure it is.

      Nice explanation Jethro. Thanks much.!!
Re: Array of Hashes or Hash of Arrays
by cdarke (Prior) on May 10, 2012 at 09:48 UTC
    thing?
    key_list_by_value is a hash - you can tell by the { }.

    $value is a hash key (looks like someone did a reverse() on %by_key. $key is a scalar.

    $key_list_by_value{$value} is a reference to an array - hence the @{  }.

      Didn't quite understand your last statement.. Can you please help to clarify? $key_list_by_value{$value} is a reference to an array - hence the @{ }.
Re: Array of Hashes or Hash of Arrays
by sumeetgrover (Monk) on May 10, 2012 at 11:15 UTC

    Ok. Here's what seems to be happening in these two statements:

    • 1. In the while loop, the pairs of Keys and Values from the hash %by_key are being fetched.
    • 2. First things first: $key_list_by_value{$value}.key_list_by_value is a hash variable, which appears to contain array-refs, hence the use of @{ } around this variable.
    • 3. What this second line of code is doing is that it is adding the current $key to the list pointed to by the current array-ref

    Here's the understandable version of this code:

    while(($key,$value)=each(%by_key) { $current_key_list_aref = $key_list_by_value{$value}; push(@$current_key_list_aref,$key); }