perl - Avoid "printf" from printing zeros on empty values -


i wonder how avoid getting zeros printf when printing undefined value or empty string perl:

$ perl -le 'printf "%.4f", undef' 0.0000 

this little c program tells me that's way printf works.

#include <stdio.h> main() {     printf ("%.4f\n", ""); } 

is there anyway within printf avoid printing zeros?

the c program tells nothing. has undefined behavior, because "" not of correct type format string.

you're getting floating-point output because that's asked using "%.4f".

in perl, if print using printf "%.4f", ..., treat argument real number , format accordingly. special value undef apparently treated 0.0 in context. if want print empty string (or, equivalently, print nothing) undef argument, need use different format string -- or not call printf @ all.

if (defined $foo) {     printf "%.4f", $foo; } 

note checks whether $foo defined, not whether it's numeric. if value of $foo reference, example, you'll meaningless numeric representation of memory address.


Comments