1. 程式人生 > 其它 >[ Skill ] print println printf fprintf sprintf lsprintf

[ Skill ] print println printf fprintf sprintf lsprintf

https://www.cnblogs.com/yeungchie/

幾種 print 函式的差異

print

  • 接收任意的資料型別
print( 12345 )        ; 12345
print( "YEUNGCHIE" )  ; "YEUNGCHIE"
print( winId )        ; window:1
print( cvId )         ; db:0x21e4c01a
  • 第二引數可選指定 IO 控制代碼
print( "String" port )
  • 返回值恆為 nil

println

  • print 區別在於 println 列印一個數據後會自動換行

舉個例子,同時執行 3 個 print

print( 1 ) print( 2 ) print( 3 )
; 123

同時執行 3 個 println

println( 1 ) println( 2 ) println( 3 )
; 1
; 2
; 3

printf

  • 格式化輸出字串
  • 第一個引數定義輸出字串格式 format,可以內插 % 格式化字元
  • 從第二個引數開始會依次替換 format 中定義的 %
who = "YEUNGCHIE"
printf( "My name is %s and weight is %d kg\n" who 999 )
; My name is YEUNGCHIE and weight is 999 kg
  • 輸出成功,返回 t,輸出不成功都是報 error。

更詳細的使用方法可以看以前的這篇隨筆 [ Skill ] 中的通用輸出格式規範

fprintf

  • printf 的區別是,用來輸出到 IO 控制代碼(可以用來輸出到檔案)
file = outfile( "~/text.txt" )
fprintf( file "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
close(file)
  • 將會生成一個檔案 ~/text.txt
> cat ~/text.txt
My name is YEUNGCHIE and weight is 999 kg
  • 成功輸出到檔案即返回 t

sprintf

  • fprintf 的區別是,用來輸出到 變數
sprintf( variable "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
variable = sprintf( nil "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
; "My name is YEUNGCHIE and weight is 999 kg"

上面兩句的效果是一樣的,variable 將會被賦值為格式化後的字串。

  • 成功格式化即返回字串內容

lsprintf

  • sprintf 的區別是,第一個引數不用於指定被賦值的變數。
string = lsprintf( "My name is %s and weight is %d kg\n" "YEUNGCHIE" 999 )
  • 成功格式化即返回字串內容
  • 當輸出的引數數量不確定的時候這個函式非常好用,舉個例子:
format = "My name is %s and weight is %d kg\n"
args   = list( "YEUNGCHIE" 999 )
string = apply( 'lsprintf format args )
; "My name is YEUNGCHIE and weight is 999 kg"
  • 當然 sprintf 也不是做不到,只不過會比較麻煩。
string = apply(
  lambda(( a \@rest b )
    apply( 'sprintf nil a b )
  )
  format
  args
)
; "My name is YEUNGCHIE and weight is 999 kg"