B
Bryan
Hi, I need a function that will remove any elements of the second array
from the first. I found a function that does mostly what I want but its
not behaving the way I want in one case.
For example, if I have two arrays;
@a1 = (1, 2, 3, 4, 5);
@a2 = (2, 4);
@a1 = sub removeArrayElements(\@a1, \@a2);
This works just fine, and @a1 = (1, 3, 5);
But if @a1 is empty;
@a1 = ();
@a2 = (2, 4);
The function returns @a1 = (4, 2), when I would like it to return ().
I believe the basic functionality for this function is from the perl
cookbook, so maybe Im using the wrong thing (don't have the cookbook
handy). Or is this the right function and it just needs to be tweaked?
Thanks,
B
sub removeArrayElements {
my ($a, $b) = @_;
my @a = @$a;
my @b = @$b;
my (@diff,%count);
my (%HASH_A,%HASH_B);
# build hashes to remove redundant elements
@HASH_A{@a}=(); # hash slice, sets @a as keys of %HASH_A
@HASH_B{@b}=();
# set $count{$e} to 2 if the element exists in both hashes
# $count{$e} will be 1 if the element is unique
foreach my $e (keys %HASH_A,keys %HASH_B) { $count{$e}++ }
# writes the hash key (the element) to @diff if it is unique
foreach my $e (keys %count) {
push @diff, $e if ($count{$e} == 1);
}
return @diff;
}
from the first. I found a function that does mostly what I want but its
not behaving the way I want in one case.
For example, if I have two arrays;
@a1 = (1, 2, 3, 4, 5);
@a2 = (2, 4);
@a1 = sub removeArrayElements(\@a1, \@a2);
This works just fine, and @a1 = (1, 3, 5);
But if @a1 is empty;
@a1 = ();
@a2 = (2, 4);
The function returns @a1 = (4, 2), when I would like it to return ().
I believe the basic functionality for this function is from the perl
cookbook, so maybe Im using the wrong thing (don't have the cookbook
handy). Or is this the right function and it just needs to be tweaked?
Thanks,
B
sub removeArrayElements {
my ($a, $b) = @_;
my @a = @$a;
my @b = @$b;
my (@diff,%count);
my (%HASH_A,%HASH_B);
# build hashes to remove redundant elements
@HASH_A{@a}=(); # hash slice, sets @a as keys of %HASH_A
@HASH_B{@b}=();
# set $count{$e} to 2 if the element exists in both hashes
# $count{$e} will be 1 if the element is unique
foreach my $e (keys %HASH_A,keys %HASH_B) { $count{$e}++ }
# writes the hash key (the element) to @diff if it is unique
foreach my $e (keys %count) {
push @diff, $e if ($count{$e} == 1);
}
return @diff;
}