Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Comparing two arrays to see if identical

Status
Not open for further replies.

mountainbiker

Programmer
Aug 21, 2002
122
GB
Lets say we have 5 arrays, i.e.,

@a1, @a2, @a3, @a4, and @a5

Each array contains a list of path/filename. Each array is sorted, so if arrays are the same each corresponding element are the same, e.g.,

$a4[1] eq $a5[1], $a4[2] eq $a5[2], and so on.

Problem:
I want to compare each array against the other, so I keep only one copy. The copy I want to keep has the higer number in its array name. For example,

if @a1, @a3, and @a5 are identical and @a2 and @a4 are identical--I would be left with @a4 and @a5. (The other arrays can just be set to ().)


 
How about something like this?

@arraynames = qw(a1 a2 a3 a4 a5);

@a1 = qw(1 2 3 4 5);
@a2 = qw(1 2 3 4 5 6);
@a3 = qw(1 2 3 4 5 6);
@a4 = qw(1 2 3 4 5);
@a5 = qw(1 2 3 4 5);

print "a1=@a1\na2=@a2\na3=@a3\na4=@a4\na5=@a5\n";

foreach $a ( @arraynames ) {
foreach $b ( @arraynames ) {
next if ($a eq $b);
@{$a} = () if ( compare_arrays( \@{$a}, \@{$b} ) );
}
print "\n";
}

print "a1=@a1\na2=@a2\na3=@a3\na4=@a4\na5=@a5\n";

sub compare_arrays {
my ($first, $second) = @_;
no warnings; # 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;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top