in reply to how to compare elements of two multi-dimensional arrays

I didn't completly understand your data structure, but I'm trying to give you some advice:
The most basic way to merge two data structures is walking through the first, item by item, and for each item go through the second searching for matches:
for my $a (@array1) { for my $b (@array2) { next if $a ne $b; # Do whatever tests you need here # Do the work here } }
Sometimes index, grep and others could be used to replace the inner loop.
Another idea would be indexing your second array by converting it into a hash. Now you could easily access each item when walking through the first array.

Replies are listed 'Best First'.
Re^2: how to compare elements of two multi-dimensional arrays
by GrandFather (Saint) on Oct 05, 2009 at 10:44 UTC

    Your last idea is by far the best solution. In fact the order in which you present the different techniques is exactly the progression taken by most people learning Perl (the trade off tends to be different for other languages). The equivalent of your nested loop using hashes is:

    for my $element (@array) { next if ! exists $lookup{$element}; # Do the work here }

    Although grep code often looks nice and clean (or at least compact), it is a nested loop and has the same trouble with performance when the arrays are large as the explicit nested loop you presented as a first try.

    btw, even for sample code don't use $a and $b - they are special variables used by sort. Unless you are golfing or writing obfuscated code avoid bed habits, especially when trying to teach someone else good habits. ;)


    True laziness is hard work