in reply to Question about dereferencing multi-dimensional array/hash

Hello jokerzy,

(I used Data::Dumper to print the hash out, and I think it's a hash of arrays of (ref to) hash, correct?)

Actually, it’s a hash of refs to anonymous arrays, the elements of which are refs to anonymous hashes — but you’ve got the idea! :-)

As to the code, frozenwithjoy had the right intuition: the logic of your inner loop is incorrect. However, the fix requires a different approach:

#! perl use strict; use warnings; use Data::Dumper; my %main_hash = ( keyA => [ { keya => 'vala' }, { keyb => 'valb' }, { keyc => 'valc' }, { keyd => 'vald' }, ], keyB => [ { keye => 'vale' }, { keyf => 'valf' }, { keyg => 'valg' }, { keyh => 'valh' }, ], keyC => [ { keyi => 'vali' }, { keyj => 'valj' }, ], ); print Dumper(%main_hash), "\n"; foreach my $k (sort keys %main_hash) { my @array = @{ $main_hash{$k} }; foreach my $i (1 .. $#array) { my %inner_hash_first = %{ $array[$i - 1] }; my %inner_hash_next = %{ $array[$i ] }; my ($first_key, $first_val) = each( %inner_hash_first ); my ($next_key, $next_val) = each( %inner_hash_next ); print "Now compare ($first_key : $first_val) with ($next_key : + $next_val)\n"; } }

Note in the above script that dereferencing has been decomposed into separate stages by using intermediate variables (@array, %inner_hash_first, and %inner_hash_next). This is a good idea for two reasons:

  1. It makes the code clearer, and so easier to follow and debug.
  2. In some cases it also promotes efficiency: for example, @{ $main_hash{$k} } is now re-calculated only once for each new value of $k.

The output from the above script is:

Now compare (keya : vala) with (keyb : valb) Now compare (keyb : valb) with (keyc : valc) Now compare (keyc : valc) with (keyd : vald) Now compare (keye : vale) with (keyf : valf) Now compare (keyf : valf) with (keyg : valg) Now compare (keyg : valg) with (keyh : valh) Now compare (keyi : vali) with (keyj : valj)

which shows that each value of each inner hash is available for comparison with its successor (if it has one), as required.

(You should probably also add a check to verify that each inner hash contains exactly one key/value pair.)

Update

Is that a pseudo-hash I'm using here?

No, according to perldoc, pseudohashes “have been removed from Perl.” See the old thread My views on pseudohashes.

HTH,

Athanasius <°(((><contra mundum

Replies are listed 'Best First'.
Re^2: Question about dereferencing multi-dimensional array/hash
by jokerzy (Initiate) on Jun 19, 2012 at 02:37 UTC
    Hi Athanasius, <== My first link to another user :)

    Thanks for the help. I like to way your code is written, especially how they're broken into different sections; it was very easy to grasp. Thanks also for the update about my pseudo-hash question.

    Signing off,
    jokerzy