perldebuggingundef

Perl debugging: Variable being set to `1` is set to `undef` unexpectedly


Note: Please read carefully; it's odd (unless I have tomatoes on my eyes)

I was changing a program of mine when it suddenly stopped to work as intended, and I failed to find the reason. Eventually I found it; please consider this Perl debugger session extract (Perl 5.18.2):

  DB<8> x $result
0  undef
  DB<9> c
main::receive_message(./syslogd.pl:1555):
1555:           $result = 1;
  DB<9> x $result
0  ARRAY(0x375cdb0)
   0  IO::Socket::INET=GLOB(0x2f8aa20)
      -> *Symbol::GEN3
            FileHandle({*Symbol::GEN3}) => fileno(6)
   1  SocketAddress=ARRAY(0x375d188)
      0  'v04:36766'
      1  'v04'
      2  36766
      3  ''
   2  '<22>May 23 10:22:07 v04 postfix/cleanup[22002]: F26AB68046: message-id=<1653294126.782e1e75c78c74d3@v04>'
  DB<10> n
main::receive_message(./syslogd.pl:1561):
1561:       $lc->verbose(3, "$me: returning " . Class::_format_undef($result));
  DB<10> x $result
0  undef

So in line 1555 $result will be set to 1 (inside an if-else block). Before $result is an ARRAY ref (as seeen). However after the line was executed (by n), the value of $result is undef, not 1 (right after the if-else block, thus a few lines later).

As the result will be returned, the caller sees the wrong result value and fails.

Unfortunately either me or Perl is heavily confused. Who can explain?


Solution

  • The tomatoes fell of my eyes! (I'm providing this answer instead of deleting the question just in case someone will ever see a similar problem)

    The code basically was:

    sub receive_message($$$$;$)
    {
        #...
        my $result;
        my $lc = $err_mh->log_config();
    
        if (defined(my $result = $lsa->receive(undef, MAXLEN, $flags))) {
            #...
            $result = 1;   # line 1555
        } else {
            #...
        }
        $lc->verbose(3, "$me: returning " . Class::_format_undef($result)); # line 1561
        return $result;
    }
    

    So the error was: "a my too much" (in the if).