mrb's blog

Perl Numeric Expressions And Backslashes

Keywords: bug hardware perl

I just wasted 30 minutes of my time trying to figure out a strange bug in a Perl script generating Atmel AVR assembly code —for a hardware hacking project I will blog about soon. A function was computing an odd parity bit, and it was generating a correct bit only in some cases...

As it turns out, this was due to unintentional backslashes at the end of lines in a numeric expression (the code was copied from a C macro). Judge by yourself:

$ cat broken.pl
#!/usr/bin/perl -w
use strict;
printf "A = %d\n", (1 ^ \
    1);
printf "B = %d\n", (1 ^
    1);
$ ./broken.pl
A = 135611809
B = 0

I am puzzled as to how Perl is interpreting my code. Why is the backslash causing it to return a non-zero value for "A"? And why, with warnings and strict mode enabled, does Perl think a human writing this code knows exactly what he is doing and would expect this kind of result without throwing a warning.

It is 4am and I cannot think straight. I will revisit this later.

[Update 2010-07-27 11:38pm: the newline between the backslash and the digit 1 was making it less obvious, but a night of sleep made it more so: Perl was treating this as a reference to 1, and was XORing the value of the reference —effectively a memory address— instead of the value 1.]

Comments

darul75 wrote: Mais à quoi tu pensais pour ne pas avoir trouvé tout de suite :) 04 Aug 2010 09:46 UTC