Dnamonk3:
Typically you use hashes when you want to compare the contents of arrays to find all matches. You might find something like this more useful:
my %temp_for_compare;
# Add values from the first array into the temporary hash
$temp_for_compare{$_} = 0 for @array1;
# Now we can simply check the items in the second array against the ha
+sh
for my $val (@array2) {
if (exists $temp_for_compare{$val}) {
print "$val in both arrays\n";
}
}
As you can see, it's fairly straightforward.
You can do it with arrays, but you either get something slow or something a little more complex. The slow version
is to simply compare each item in the array with each item in the other array. Don't do it this way!:
for my $a1val (@array1) {
for my $a2val (@array2) {
if ($a1val eq $a2val) {
print "$a1val in both arrays\n";
}
}
}
The problem with doing it this way is that while it's simple, it gets slow pretty quickly. If you have 100 items in each array, then you run through the loop 100*100 times.
With a little more code, you can make it better by sorting the arrays and checking them pairwise. First, you'll
have to sort your arrays. Since it's a destructive procedure, you'll want to make copies of your arrays if you want to
keep them around after the comparison. Then you simply check the first value of each array: If they match, you found a
pair of values in both arrays. Otherwise, you discard the smaller of the two values and check again. You stop when one
of the arrays is empty:
my @tmpArray1 = sort @array1;
my @tmpArray2 = sort @array2;
# You run out of matches when either array is empty
while (@tmpArray1 and @tmpArray2) {
if ($tmpArray1[0] eq $tmpArray2[0]) {
print "$tmpArray1[0] in both arrays\n";
shift @tmpArray1;
shift @tmpArray2;
}
elsif ($tmpArray1[0] lt $tmpArray2[0]) {
# tmpArray1 has an item not in tmpArray2, so get rid of
# it and try the next element
shift @tmpArray1;
}
else {
# tmpArray2 has an item not in tmpArray1, so get rid of
# it and try next element
shift @tmpArray2;
}
}
If you have 100 items in each array, you run through the loop at most 200 times. (Of course, you have the added time penalty of the sort operation.)
If you compare it to the hash operation, then you have a loop of 100 operations to build the hash, and then 100 operations to check the other array against the hash.
...roboticus
When your only tool is a hammer, all problems look like your thumb. |