2

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

Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
Martin Sloan
  • 119
  • 10
  • Whilst this problem is better solved using the keys of a hash as a set, on a programming point your inner loop is potentially dicey in that it could hang if `$num` doesn't appear in `@reserve`. Also your values appear to be numbers, but you're comparing them using `eq`, the *string* equality operator. – zgpmax Mar 14 '12 at 16:18

2 Answers2

3

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 ;
dgw
  • 13,418
  • 11
  • 56
  • 54
1

How about:

my @system = query();
my @reserve = 11000..136000;
my %tmp = map{$_ => 1}@system;
@reserve = grep{!exists $tmp{$_}}@reserve;
Toto
  • 89,455
  • 62
  • 89
  • 125