'Perl inconsistently prints strings that contain specific combinations of '%'

Can anyone please explain this perl behavior that i came across?

printf("%what_the\n");
printf("\%what_the\n");

Prints:

%what_the
%what_the

WHILE...

printf("%tomorrow\n");
printf("\%tomorrow\n");

Prints:

0morrow
0morrow

...EVEN WITH warnings and strict:

use strict;
use warnings;
printf("\%tomorrow\n");

Prints:

Missing argument in printf at - line 3.
0morrow


Solution 1:[1]

printf is different from regular print. You might be thinking it is the same, it is not. printf takes a pattern, which includes %. For example:

printf "%s\n", "tomorrow";   # prints "tomorrow\n"

%s is a placeholder for a string, which should be the second argument to printf.

The warning you get shows you the problem

Missing argument in printf at - line 3.

printf expects a second argument, because you have supplied a placeholder.

Not all letters following a percent sign is a valid combination, here's a few from the documentation from sprintf

%%    a percent sign
%c    a character with the given number
%s    a string
%d    a signed integer, in decimal
%u    an unsigned integer, in decimal
%o    an unsigned integer, in octal
%x    an unsigned integer, in hexadecimal
%e    a floating-point number, in scientific notation
%f    a floating-point number, in fixed decimal notation
%g    a floating-point number, in %e or %f notation
.... more

I do not see %to in there, but it seems to be what is being triggered. It prints a 0 because it casts the empty string (missing argument) to 0.

Documentation here.

Solution 2:[2]

The way to escape a % sign is to double it, not by a backslash. %o is the format for printing an octal number. Try doing printf "%tomorrow", 255;. The t is a modifier flag on %o to set the integer type.

https://perldoc.perl.org/functions/sprintf#size

HTH

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 lordadmira