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

Hi all, Whats the best way to compare the contents of array @a with the contents of @b and then put everything from @b that is not in @a into another list @c. Does that make sense? I'm doing an FTP script that reads all already transfered files into one list and all the files on the remote machine into another list. I need to compare them so that I don't retransfer existing files. many many thanks, Doug.

Replies are listed 'Best First'.
Re: Howto Compare 2 lists
by reasonablekeith (Deacon) on Sep 14, 2005 at 10:45 UTC
    List::Util
    and
    List::MoreUtils
    are your friends
    ---
    my name's not Keith, and I'm not reasonable.
      having said that you could roll your own...
      #!/usr/bin/perl -w use strict; my @a = (1,2,3); my @b = (1,2,3,4,5); my %a_lookup = map {$_,undef} @a; my @c = grep {! exists $a_lookup{$_}} @b; print join(',', @c) . "\n"; # __OUTPUT__ # 4,5
      ---
      my name's not Keith, and I'm not reasonable.
Re: Howto Compare 2 lists
by inman (Curate) on Sep 14, 2005 at 10:49 UTC
    Have you looked at the Q&A section on arrays? There are a number of variations that may be interesting.

    You can use grep to find the members of list_a that are not members of list_b all in the same line of code.

    my @list_a = qw (3 1 2 5 4); my @list_b = qw (5 3 6 2 7 1 4); my @list_c = grep {my $x=$_; !grep {$x==$_} @list_a} @list_b; print "@list_c";
    The use of multiple greps is expensive where @list_a is larger than a few elements. A hash lookup would be preferred.
Re: Howto Compare 2 lists
by prasadbabu (Prior) on Sep 14, 2005 at 10:56 UTC
      Thanks all. I've used the List::Compare::Functional module which works a treat.

      Doug.