PERL: simple comparing arrays question

Hi there, i have been trying different methods and i wonder if somebody could explain to me how i would perform a comparison on two arrays for example

my @array1 = ("gary" ,"peter", "paul");
my @array2 = ("gary" ,"peter", "joe");

I have two arrays above, and i want to something like this

for my $name ( sort (@array1)) {
	if (! exists $array2[$_]) {
            print "$name does not exist in array2";
        } else { 
            print "woo hoo $name exists in both arrays";
        }
}

the code above does not work, but hopefully, you'll get from it the general idea of what im trying to do.. the line that is bugging me is the one directly under the "for" statement ....i know that line is screwed but i cant seem to work out how to test the existence of the $name variable in the other array

its probably a really simple fix to my above code but any help on this would be greatly appreciated

In your "if", what is the value of "$_"? Did you take a hash example and try to convert it to work on lists?

What you want to do in the if is iterate over the second list. One solution:

for my $name ( sort (@array1)) {
  my $found = 0;
  foreach (@array2) {
    if ( $name eq $_ ) { $found++; }
  }
  if ( $found ) {
    print "woo hoo $name exists in both arrays\n";
  } else {
    print "$name does not exist in array2\n";
  }
}

perl has a grep function which is supposed to iterate over the list for you so you might also look at that.

Something like this:

perl -le'
	@a1 = qw(gary peter paul);
	@a2 = qw(gary peter joe);

	@seen{@a2} = (1) x @a2;

	print $_, $seen{$_}
	  ? " exists "
	  : " does not exist ", "in \@a2"
	  for @a1;
  '
% perl -le'
@a1 = qw(gary peter paul);
@a2 = qw(gary peter joe);

@seen{@a2} = (1) x @a2;

print $_, $seen{$_}
  ? " exists "
  : " does not exist ", "in \@a2"
  for @a1;
  '
gary exists in @a2
peter exists in @a2
paul does not exist in @a2

search List::Compare in CPAN

With Perl 5.10 and the smart match operator:

% perl -E'
@a1 = qw(gary peter paul);
@a2 = qw(gary peter joe);
say $_, $_ ~~ @a2
  ? " exists "
  : " does not exist ",  "in \@a2"
  for @a1;
  '
gary exists in @a2
peter exists in @a2
paul does not exist in @a2

thanks guys, that has been incredibly useful and informative