0

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});
  }
}
ssr1012
  • 2,573
  • 1
  • 18
  • 30
  • 1
    `eq` is for comparing strings; `==` is for comparing numbers. Either use `if($csr eq "1")` or `if($csr == 1)`. [See here for more details](https://stackoverflow.com/a/1175398/2261424). (I haven't looked at the rest of the code, just the described error) – AntonH Feb 11 '20 at 06:33
  • 1
    The error message you show doesn't make sense -- but are you sure that `$csr` receives a value from that subroutine call? Put differently, if it doesn't you'll get a warning. (Also: you most likely don't need that `&`) – zdim Feb 11 '20 at 06:36

1 Answers1

1

$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.
ikegami
  • 367,544
  • 15
  • 269
  • 518