venerdì 16 gennaio 2015

printf and the wrong attitude: an experience

I'm so used to the way the normal print operator works in Perl that I did a silly mistake using the printf function with the same attitude: a full list of arguments.

The buggy line was like the following:

printf $format_string, @data, "\n";

Can you see the error?
Well, the new line at the end is not likely to be printed, and it was not in my case. The problem is that everything that follows the format string is managed as an argument to the format string itself. Therefore, the format string must have a placeholder for the new line charaters, as in:

$format_string = "%d %s %c ....%s";

In my case I was not placing the last %s in the format string because I used the format string itself to manage how many data to extract from the array of elements, that is something like:

printf $format_string, @data[ 0..$hint_from_command_string ], "\n";

And in order to waste a little more time, I was trying to figuring it out on a terminal that was wrapping the line length where the new line should have been, making the illusion I was looking at separated lines.
Of couse using a good text editor or some tool like head revealed I was looking at something very different: a whole line.
And that helped me finding the bug and moving the new line character into the format string at the very last moment:

printf "$format_string\n", @data;

Shame on me!

Nessun commento: