in reply to Comparing arrays

Update: In deference to Arien's concerns.

if ( do{ local$"=''; @array1 == @array2 and "@array1" eq "@array2"} ) +{ print 'They are the same', $/; }

Which of course will also break if you have two arrays,

my @a = ( 'onetwo','', 'three'); my @b = ( 'one', 'two', 'three' );

And as with any shortcuts, you need to know your data before you apply them. If your not comforable with that, don't use it.

Update more:

I'll spell it out for those unable or unwilling to make the mental leap for themselves.

If your data is wholey numeric, then use $"=<any non-numeric-char>.

If your data consists of wholey alpha data use a non-alpha char.

If your data consists of mixed alpha-numeric then use a non-alpha-numeric.

If your data can contain any char in the range 32-127, cosider using a control character (eg."\cA").

If your data can contain any 7-bit char, use an 8-bit char. 128-255.

If there is simply no character that your data does not contain, then you need to compare element-by-element. These cases are very rare. In almost all normal sets of data it is possible to find a single char that you can get away with using, and eq testing of the stringyfied arrays is a simple, and efficient way of performing this kind of test on small datasets.

Replies are listed 'Best First'.
Re: Re: Comparing arrays
by Arien (Pilgrim) on Dec 24, 2002 at 09:32 UTC

    That doesn't necessarily work as intended if the values of one or more elements in either array contain the list separator $":

    my @array1 = qw(one two three); my @array2 = ("one" . $" . "two", "three"); if ("@array1" eq "@array2") { print 'They are the same', $/; # no, they are NOT }

    The updated code is still flawed, consider:

    my @array1 = qw(one two three); my @array2 = qw(onetwo three); if ( do{ local $" = ''; "@array1" eq "@array2"} ) { print 'They are the same', $/; # no, they are NOT }

    This second update still isn't the way to do it... I took out the local $" (which should be no problem as the value of $" shouldn't matter anyway). Consider:

    my @array1 = ("one", "two" . $" . "three"); my @array2 = ("one" . $" . "two", "three"); if ( do{ @array1 == @array2 and "@array1" eq "@array2"} ) { print 'They are the same', $/; # no, they are NOT }

    Stringifying would only work if it is guaranteed that $" doesn't occur as a substring of one or more values of either array.

    — Arien