I have two arrays of strings that I would like to compare for equality:
my @array1 = ("part1", "part2", "part3", "part4");
my @array2 = ("part1", "PART2", "part3", "part4");
Is there a built-in way to compare arrays like there is for scalars?
I tried:
if (@array1 == @array2) {...}
but it just evaluated each array in scalar context, and so compared the length of each array.
I can roll my own function to do it, but it seems like such a low-level operation that there should be a built-in way to do it. Is there?
Edit: sadly, I don’t have access to 5.10+ or optional components.
There is the new smart match operator:
Regarding Array::Compare:
I guess that is a valid method, but so long as we are using string comparisons, I would much rather use something like:
If the arrays you are comparing are large, joining them is going to do a lot of work and consume a lot of memory than just comparing each element one by one.
Update: Of course, one should test such statements. Simple benchmarks:
This is the worst case scenario where
elementwise_eqhas to go through each and every element in both arrays 1_000 times and it shows:Rate iterator array_comp iterator 246/s -- -75% array_comp 1002/s 308% --On the other hand, the best case scenario is:
Rate array_comp iterator array_comp 919/s -- -98% iterator 52600/s 5622% --iteratorperformance drops quite quickly, however:Rate iterator array_comp iterator 10014/s -- -23% array_comp 13071/s 31% --I did not look at memory utilization.