in reply to comparing arrays
Here is an equality function for arrays of strings, takes references to two arrays as argument:
We check to see that the lengths are the same, return false ( not equal) if they are not. Then we use grep over the indexes to scan for unequal elements, putting the index in another array for each mismatch. Finally we return the negation of the mismath array's length as result; no mismatches gave a zero length array.sub aeq { my ($first, $second, @comp) = @_; return 0 if @{$first} != @{$second}; @comp = grep {$first->[$_] ne $second->[$_]} 0..$#$first; return not @comp; }
Update: Thanks to gmax for spotting my blunder in obtaining the last index. Fixed. For kappa's concern, I was thinking more of avoiding a run off the end of $second if it was shorter. For efficiency, I'd write this in terms of a flipflop, .. in scalar context. On reflection, I'd either do that, or in list context return an array of indexes that match:
The choice is, as you say, between efficiency and general utility. Pick efficiency if you never need to filter for matches.sub aeq { my ($first, $second, @comp) = @_; return 0 if @{$first} != @{$second}; @comp = grep {$first->[$_] eq $second->[$_]} 0..$#$first; wantarray ? @comp : @comp == @$first; }
U2 Bah, I'm suffering from a little brain damage, repaired the newer code.
After Compline,
Zaxo
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: comparing arrays
by kappa (Chaplain) on Apr 04, 2002 at 12:13 UTC |