Perl 不一致地打印包含“%”特定组合的字符串
Perl inconsistently prints strings that contain specific combinations of '%'
任何人都可以解释一下我遇到的这种 perl 行为吗?
printf("%what_the\n");
printf("\%what_the\n");
打印:
%what_the
%what_the
同时...
printf("%tomorrow\n");
printf("\%tomorrow\n");
打印:
0morrow
0morrow
...甚至 warnings
和 strict
:
use strict;
use warnings;
printf("\%tomorrow\n");
打印:
Missing argument in printf at - line 3.
0morrow
printf
不同于常规 print
。你可能会认为它是一样的,但事实并非如此。 printf
采用一种模式,其中包括 %
。例如:
printf "%s\n", "tomorrow"; # prints "tomorrow\n"
%s
是字符串的占位符,应该是printf
.
的第二个参数
您收到的警告告诉您问题所在
Missing argument in printf at - line 3.
printf
需要第二个参数,因为您提供了一个占位符。
并非百分号后的所有字母都是有效组合,这里有一些来自 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
我在那里没有看到 %to
,但它似乎是被触发的。它打印 0
因为它将空字符串(缺少参数)转换为 0
.
文档 here.
转义 % 符号的方法是将其加倍,而不是 通过反斜杠。 %o
是打印八进制数的格式。尝试做 printf "%tomorrow", 255;
。 t
是 %o
上的修饰符标志,用于设置整数类型。
https://perldoc.perl.org/functions/sprintf#size
HTH
任何人都可以解释一下我遇到的这种 perl 行为吗?
printf("%what_the\n");
printf("\%what_the\n");
打印:
%what_the
%what_the
同时...
printf("%tomorrow\n");
printf("\%tomorrow\n");
打印:
0morrow
0morrow
...甚至 warnings
和 strict
:
use strict;
use warnings;
printf("\%tomorrow\n");
打印:
Missing argument in printf at - line 3.
0morrow
printf
不同于常规 print
。你可能会认为它是一样的,但事实并非如此。 printf
采用一种模式,其中包括 %
。例如:
printf "%s\n", "tomorrow"; # prints "tomorrow\n"
%s
是字符串的占位符,应该是printf
.
您收到的警告告诉您问题所在
Missing argument in printf at - line 3.
printf
需要第二个参数,因为您提供了一个占位符。
并非百分号后的所有字母都是有效组合,这里有一些来自 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
我在那里没有看到 %to
,但它似乎是被触发的。它打印 0
因为它将空字符串(缺少参数)转换为 0
.
文档 here.
转义 % 符号的方法是将其加倍,而不是 通过反斜杠。 %o
是打印八进制数的格式。尝试做 printf "%tomorrow", 255;
。 t
是 %o
上的修饰符标志,用于设置整数类型。
https://perldoc.perl.org/functions/sprintf#size
HTH