Rob Dixon wrote: > > Wesley Phillips wrote: > > Hi all, > > I have been working on a problem and worked out a solution, but am > > wondering if there is an easier(more elegant?) way of doing it. I am > > automatically generating configuration files for a Quality Of Service(QOS) > > device, and each pipe in the QOS has a policy number attached to it. The > > policy numbers must be unique, so I have to find an unused number. The > > system never has more than 200 or so policies. I am pulling the preexisting > > policy numbers out of a database and placing them into an array(@addarr) > > Here is my code: > > > > > > #!/usr/bin/perl > > > > use Mysql; > > > > $db = Mysql->connect('localhost', 'dbase', 'user', 'password'); > > $query = $db->query("SELECT policy FROM Table"); > > while ( $policy = $query->fetchrow_array()) { > > $addarr[$policy] = $policy; > > } > > for ($i = 1; $i < 1001; $i++) { > > if (defined($addarr[$i])) { > > next; > > } else { > > $newaddr = $i; > > last; > > } > > } > > > > where $newaddr would be the new, as yet unused, number > > Hi Wes. > > First of all, > > use strict; # always > use warnings # usually > > Secondly the Mysql module is now deprecated in favour of DBI together with > its DBD::mysql driver. > > However I can well believe that either or both of these points are dictated > by your employer, so here's the answer... > > It looks like you want the smallest number in 1 .. 1000 which doesn't already > exist in the 'policy' column of 'Table'. What I'd do is to start by setting > up a hash with all of the valid values as keys. Then simply drag in all of > the current values of this column into an array and use it to delete the > corresponding elements of the hash. The number you want is then the first > of the sorted list of remaining hash keys. It looks like this: > > use strict; > use warnings; > > use Mysql; > > my $db = Mysql->connect('localhost', 'dbase', 'user', 'password'); > > # Set up the hash with 1000 elements > # > my %policy; > @policy{1 .. 1000} = (); > > # Delete all those currently in use > # > my @current = $db->query("SELECT policy FROM Table")->fetchcol; > delete @[EMAIL PROTECTED]; > > # The next one to use is the first of those left > # > my $next = (sort keys %policy)[0];
You are sorting numbers so you should use a numerical sort otherwise '20' will be sorted after '100' etc. my $next = (sort { $a <=> $b } keys %policy)[0]; Or you could use an array: my @policy = 0 .. 1000; delete @policy[ @current ]; my $next; $next = $_ and last for @policy; John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]