對於某些字串,需要輸入為特定的格式,通過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"