Kapil Viswam
Kapil Viswam

Reputation: 15

Deleting keys from a hash map in Perl

As I am new to perl, trying to learn some basics. Don't know how relevant this is.

I have an SQL Select query which return 1 on successful execution. I also have a hashmap say

%map

For each key of this map I need to execute the SQL by giving this key as input. That is:

foreach my $key(keys %map){

  my ($temp, $csr) = &the_fetchonerow_sql($sql, 1, $key);
}

If the sql returns 1 then that correspondiong key must be deleted from the map.

Can anybody help me with the code.

Here is the part of the code I tried, but I am getting an error "use of uninitialized variable eq".

foreach my $key(keys %map){

  my ($temp, $csr) = &the_fetchonerow_sql($sql, 1, $key);
  if($csr eq 1){
    delete($map{$key});
  }
}

Upvotes: 0

Views: 101

Answers (1)

ikegami
ikegami

Reputation: 385506

$csr is apparently undef, presumably from being NULL in the db.

for my $key (keys(%map)) {
   my (undef, $csr) = the_fetchonerow_sql($sql, 1, $key);
   if (defined($csr) && $csr == 1) {
       delete($map{$key});
   }
}

If you just want to test if the value is true —1 is true, 0 and undef are false— the above simplifies to the following:

for my $key (keys(%map)) {
   my (undef, $csr) = the_fetchonerow_sql($sql, 1, $key);
   if ($csr) {
       delete($map{$key});
   }
}

or

for my $key (keys(%map)) {
   my (undef, $csr) = the_fetchonerow_sql($sql, 1, $key);
   delete($map{$key}) if $csr;
}

Notes:

  • == is used to compare numbers. eq is for strings.
  • I removed the &. It shouldn't be there.
  • If you ever call a variable "temp", you are doing something wrong. It's the most useless name possible.
  • And you couldn't come up with anything better than $key in non-generic code? Even $id would be better if it's a row id.
  • No need to declare a variable you don't use.
  • There are probably faster alternatives to executing the "same" query repeatedly.

Upvotes: 1

Related Questions