对于某些字符串,需要输入为特定的格式,通过sprintf可以很方便的完成,不需要专门进行其他处理。
perl中的sprintf的用法如下:
sprintf FORMAT, LIST
比如:
$result = sprintf("%08d",$number);让$number有8个前导零。
$rounded = sprintf("%.3f",$number);
让小数点后有3位数字。
sprintf允许的如下常用的转换:
%% 百分号
%c 把给定的数字转化为字符
%s 字符串
%d 带符号整数,十进制
%u 无符号整数,十进制
%o 无符号整数,八进制
%x 无符号整数,十六进制
%e 浮点数,科学计算法
%f 浮点数,用于固定十进制计数
%g 浮点数,包括%e和%f
%X like %x, but using upper-case letters
%E like %e, but using an upper-case "E"
%G like %g, but with an upper-case "E" (if applicable)
%b an unsigned integer, in binary
%B like %b, but using an upper-case "B" with the # flag
%p a pointer (outputs the Perl value's address in hexadecimal)
%n special: *stores* the number of characters output so far
into the next variable in the parameter list
通过$1,$2等可以改变顺序:
printf '%2$d %1$d', 12, 34; # prints "34 12"
printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1"
printf '<% d>', 12; # prints "< 12>"
printf '<%+d>', 12; # prints "<+12>"
printf '<%6s>', 12; # prints "< 12>"
printf '<%-6s>', 12; # prints "<12 >"
printf '<%06s>', 12; # prints "<000012>"
printf '<%#o>', 12; # prints "<014>"
printf '<%#x>', 12; # prints "<0xc>"
printf '<%#X>', 12; # prints "<0XC>"
printf '<%#b>', 12; # prints "<0b1100>"
printf '<%#B>', 12; # prints "<0B1100>"
printf '<%f>', 1; # prints "<1.000000>"
printf '<%.1f>', 1; # prints "<1.0>"
printf '<%.0f>', 1; # prints "<1>"
printf '<%e>', 10; # prints "<1.000000e+01>"
printf '<%.1e>', 10; # prints "<1.0e+01>"
printf '<%.6d>', 1; # prints "<000001>"
printf '<%+.6d>', 1; # prints "<+000001>"
printf '<%-10.6d>', 1; # prints "<000001 >"
printf '<%10.6d>', 1; # prints "< 000001>"
printf '<%010.6d>', 1; # prints "< 000001>"
printf '<%+10.6d>', 1; # prints "< +000001>"
printf '<%.6x>', 1; # prints "<000001>"
printf '<%#.6x>', 1; # prints "<0x000001>"
printf '<%-10.6x>', 1; # prints "<000001 >"
printf '<%10.6x>', 1; # prints "< 000001>"
printf '<%010.6x>', 1; # prints "< 000001>"
printf '<%#10.6x>', 1; # prints "< 0x000001>"
printf '<%.5s>', "truncated"; # prints "<trunc>"
printf '<%10.5s>', "truncated"; # prints "< trunc>"
printf "%2/$d %d/n", 12, 34; # will print "34
"
printf "%2/$d %d %d/n", 12, 34; # will print "34
4/n"
printf "%3/$d %d %d/n", 12, 34, 56; # will print "56
4/n"
printf "%2/$*3/$d %d/n", 12, 34, 3; # will print " 3
n"