當前位置:首頁 » Perl » Perl printf 函數

Perl printf 函數

perl printf函數例子,printf函數實例代碼 - 打印解釋,通過指定的格式格式到當前輸出文件句柄值的列表LIST,或一個指定的文件句柄。

語法

printf FILEHANDLE FORMAT, LIST

printf FORMAT, LIST


定義和用法

打印解釋,通過指定的格式格式到當前輸出文件句柄值的列表LIST,或一個指定的文件句柄。

實際上相當於打印FILEHANDLE的sprintf(FORMAT,LIST)

您可以使用printf打印的情況:如果你並不需要一個特定的輸出格式。

以下是公認的格式轉換。

Format Result
%% A percent sign
%c A character with the given ASCII code
%s A string
%d A signed integer (decimal)
%u An unsigned integer (decimal)
%o An unsigned integer (octal)
%x An unsigned integer (hexadecimal)
%X An unsigned integer (hexadecimal using uppercase characters)
%e A floating point number (scientific notation)
%E A floating point number, uses E instead of e
%f A floating point number (fixed decimal notation)
%g A floating point number (%e or %f notation according to value size)
%G A floating point number (as %g, but using .E. in place of .e. when appropriate)
%p A pointer (prints the memory address of the value in hexadecimal)
%n Stores the number of characters output so far into the next variable in the parameter list

Perl也支持,有選擇地調整輸出格式的標誌。這些被指定%和轉換字母。它們顯示在下麵的表中:

Flag Result
space Prefix positive number with a space
+ Prefix positive number with a plus sign
- Left-justify within field
0 Use zeros, not spaces, to right-justify
# Prefix non-zero octal with .0. and hexadecimal with .0x.
number Minimum field width
.number Specify precision (number of digits after decimal point) for floating point numbers
l Interpret integer as C-type .long. or .unsigned long.
h Interpret integer as C-type .short. or .unsigned short.
V Interpret integer as Perl.s standard integer type
v Interpret the string as a series of integers and output as numbers separated by periods or by an arbitrary string extracted from the argument when the flag is preceded by *.

返回值

  • 0 - 失敗

  • 1 - 成功

例子

試試下麵的例子:

#!/usr/bin/perl -w
#by www.gitbook.net

printf "%d\n", 3.1415126;
printf "The cost is \$%6.2f\n",499;
printf "Perl's version is v%vd\n",%^V;
printf "d\n", 20;

這將產生以下結果:自己可嘗試更多的選擇。

3
The cost is $499.00
Perl's version is v
0020