Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to compair an array with two elements to a list of two known values. The only solution I have been able to come up with that works correctly is to assign the known list to another array and compair the two.
@dud=("1", "")
@dud eq ("1", "") #Does not equal 1.
@dud2=("1", "")
@dud eq @dud2 #Does equal 1.
I also tried using the brackets instead of parenthesis but that didn't work either.

Replies are listed 'Best First'.
RE: Comparing arrays
by chromatic (Archbishop) on Mar 20, 2000 at 23:11 UTC
      Doesn't look like that FAQ is loaded into PerlMonks...

      Read it on language.perl.com instead.

RE: Comparing arrays
by Anonymous Monk on Mar 22, 2000 at 01:31 UTC
    remember that eq does a string compare and not an array compare
Re: Comparing arrays
by Anonymous Monk on Mar 21, 2000 at 02:38 UTC
    Here's a succint but untested solution. If you're comparing lists or hashes of numbers, just replace eq with ==. If you don't like or don't understand Perl prototypes... well, too bad :)
    # returns the largest element in a list sub max(@) { (sort @_)[-1] } # returns the union of two lists - i.e., all elements which are in at +least one list sub union(@@) { ++$f{$_} foreach (@{$_[0]}, @{$_[1]}); keys %f } } # compares two list values for equality, by way of scalar(grep) # note that it takes into account the possibility of lists of differen +t sizes sub lst_eq(@@) { scalar (grep { $_[0][$_] eq $_[1][$_] } (0..max ($#{$ +_[0]}, $#{$_[1]})) } # compares two hashes for equality, by way of scalar(grep) # note that it takes into account the possibility of hashes with diffe +rent keys sub hsh_eq(%%) { scalar (grep { $_[0]{$_} eq $_[1]{$_} } union (keys ( +%{$_[0]}), keys (%{$_[0]}))) }
      You shouldn't use grep in this context, because grep will search through an entire array no matter what--in other words, it'll do a lot of extra work. If you write up your own routine, you can break out of the compare loop as soon as you find two elements that aren't equal. This is good.

      Use the code from the FAQ!

      $are_equal = compare_arrays(\@frogs, \@toads); sub compare_arrays { my ($first, $second) = @_; local $^W = 0; # silence spurious -w undef complaints return 0 unless @$first == @$second; for (my $i = 0; $i < @$first; $i++) { return 0 if $first->[$i] ne $second->[$i]; } return 1; }
      In particular, note this line:
      return 0 unless @$first == @$second;
      So the routine returns automatically if the arrays aren't of equal size. In your algorithm, you compare the elements in the arrays even if they're of different sizes. In fact, you explicitly wrote this in using your max function! Why? If the arrays aren't the same size, how could they possibly be equal?

      Also, look at the FreezeThaw examples in the FAQ.