
BillKSmith
Veteran
Feb 7, 2013, 7:32 AM
Post #4 of 6
(1532 views)
|
Re: [alanj] Fast matching in 2 arrays
[In reply to]
|
Can't Post
|
|
Your posted code was consistent with the X's in your text. I assumed that it was pasted into your post correctly. Whenever you want to compare arrays think of a hash. The following code requires memory for a large hash, but should be much faster because it eliminates the inner loop.
use strict; use warnings; use Data::Dumper qw(Dumper); my @Array1 = ( [1,'a'], [2,'b'], [3,'c'], ); my @Array2 = ( [7,'x'], [2,'y'], [9,'z'], ); my %hash2; for my $j ( 0 .. $#Array2 ) { $hash2{ $Array2[$j][0] } = $j; } my @Array3; for my $i ( 0 .. $#Array1 ) { next if !exists $hash2{ $Array1[$i][0] }; # Found a match so populate new array. my $j = $hash2{ $Array1[$i][0] }; $Array3[$i][0] = $Array1[$i][0]; $Array3[$i][1] = $Array1[$i][1] . "," . $Array2[$j][1] . "," . $j; } print Dumper( \@Array3 ); OutPut
$VAR1 = [ undef, [ 2, 'b,y,1' ] ]; Good Luck, Bill
|