Perl Compare 2 Arrays

Hello,

Consider the following 2 arrays:

 
Array1 = qw(Fa0/0 Fa0/1 Fa0/2 Fa0/3);
Array1 = qw(Fa0/1 Fa0/2 Fa0/3 Fa0/4);

I want to compare the following 2 arrays as follows:

  • Take specific action when elements of Array1 that doesn't exist in Array2 (in my example: Fa0/0).
  • Take another action when elements of Array2 that doesn't exist in Array1 (in my example: Fa0/4).

please advise.

# That can be done by hashes concept
@Array1 = qw(Fa0/0 Fa0/1 Fa0/2 Fa0/3);
@Array2 = qw(Fa0/1 Fa0/2 Fa0/3 Fa0/4);
# process two array , increment the values and store into hash
$hash{$_}++ for (@Array1, @Array2);
for (keys %hash)
{
 # print the value equal to one 
 print "\n$_" if ($hash{$_} == 1);
}

For more details go to command mode and process the below command

 
perldoc -q unique
1 Like

Hello,

Many thanks for your support.

It works well and I got the both Fa0/0 and Fa0/4.

but as I mentioned first, I want to run a differnt actions for both output (action if element in array1 doesn't exist in array2 and different action if element in array2 doesn't exist in array1).

Also it doesn't work properly when the array has duplicate values (this possible in my case).

Appreaciate your reply.

Regards,
Ahmed

# Declare your array's
@Array1 = qw(Fa0/0 Fa0/1 Fa0/2 Fa0/3);
@Array2 = qw(Fa0/1 Fa0/2 Fa0/3 Fa0/4);
# compare array1 elements to array2 elements
foreach $key1 ( @Array1)
{
 $flag=0; # set the flage value
 foreach $key2 ( @Array2)
 {
  if ($key1 eq $key2)
  {
   $flag=1;
   next;
  }
 }
 # that considered array 1 element doesn't match array2 elements
 if ($flag == 0 ) 
 {
  print "\nValue '$key1' doesn't exist in \@Array2";
  ## Do your actions here
 }
   
}
# use the above logic and compare array2 to array1
# Your stuff's Here

Hi.

See also the module:

NAME
       List::Compare - Compare elements of two or more lists

VERSION
       This document refers to version 0.37 of List::Compare.  This version
       was released June 07, 2008.

SYNOPSIS
       The bare essentials:

           @Llist = qw(abel abel baker camera delta edward fargo golfer);
           @Rlist = qw(baker camera delta delta edward fargo golfer hilton);

           $lc = List::Compare->new(\@Llist, \@Rlist);

           @intersection = $lc->get_intersection;
           @union = $lc->get_union;

       ... and so forth.

-- excerpt from perldoc List::Compare, q.v.

Depending on your system, you may need to install List::Compare ... cheers, drl