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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Removing an element from array 1

Status
Not open for further replies.

perln00b

Programmer
Oct 4, 2005
21
US
Support I have two arrays, and each of them doesn't have repeat elements. And compare the first array to the second one, if element repeats in 2nd array, the element has to be removed from the 1st one. i.e.
###################################################
@arry1 = ("1", "2", "3");
@arry2 = ("9", "10", "1");
###################################################

So, "1" is the common element for both arrays, but I only need to remove it from the 1st array.

Does anyone have any idea to handle this?

Thanks,
Lucas
 
Not much different, only it doesn't use a temporary array:
Code:
my @a1 = qw(1 R 3 5 7 9 X 12 2 W 3);
my @a2 = qw(2 5 4 9 1 X);
my %a2_hash = map {$_,1} @a2;
@a1 = grep {! defined $a2_hash{$_}} @a1;
print "@a1";
Since splice was used in a couple of the examples, and this might be a bit easier to understand for the newer guys (or maybe not?), here's a different way to go about it:
Code:
my %a2_hash;
foreach (@a2) {
    $a2_hash{$_}=1;
}

for (my $i=0; $i <= $#a1; $i++) {
    if (exists $a2_hash{$a1[$i]}) {
        splice(@a1, $i, 1);
        redo; # Doesn't increment $i
    }
}
print "@a1";[/code]
 
Hi rharsh

You are right - it is a crap solution!


Kind Regards
Duncan
 
orangegal,

if you have this:

@arry1 = ("1", "2", "3");
@arry2 = ("9", "10", "1");

and want to get rid of the duplicate (1) you could pop @arry2, but thats only going to work if you know the order and the values of both arrays beforehand. The above example is not going to be the real data though.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top