Compare 2 arrays and remove matches
-
13-12-2019 - |
Question
I have 2 arrays (@system
,@reserve
). Each contain a list of numbers and I'd like to compare and splice out (maybe?) the numbers in @reserve
which match numbers in @system
.
I've tried some of the responses to find and splice questions out there, but they don't seem to be working. Using Perl 5.12.4.
Numbers in @reserve
will always be 11000..136000 and the numbers in system will always be within the @system
range but will vary. The code that I've been focusing on looks like:
my @system = query();
my @reserve = 11000..136000;
foreach my $num (@system) {
my $index = 0;
$index++ until $reserve[$index] eq $num;
splice (@reserve,$index,1);
}
query() just asks the system (PBX) for a list of numbers and pushes them into @system
.
Any help is appreciated.
Thanks,
Marty
Solution
You don't have to work with splice
when you use a hashslice instead:
my @system = query();
my %reserve ;
@reserve{(11000..136000)} = undef ;
delete @reserve{@system} ;
my @list_of_reserve = sort { $a <=> $b } keys %reserve ;
OTHER TIPS
How about:
my @system = query();
my @reserve = 11000..136000;
my %tmp = map{$_ => 1}@system;
@reserve = grep{!exists $tmp{$_}}@reserve;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow