Erlang 輸出至終端

2022-07-07 15:38 更新

Erlang輸出至終端

用例子來(lái)說(shuō)明如何格式化輸出到終端再好不過(guò)了,因此下面就用一個(gè)簡(jiǎn)單的示例程序來(lái)說(shuō)明如何使用 io:format 函數(shù)。與其它導(dǎo)出的函數(shù)一樣,你可以在 shell 中測(cè)試 io:format 函數(shù):

31> io:format("hello world~n", []).
hello world
ok
32> io:format("this outputs one Erlang term: ~w~n", [hello]).
this outputs one Erlang term: hello
ok
33> io:format("this outputs two Erlang terms: ~w~w~n", [hello, world]).
this outputs two Erlang terms: helloworld
ok
34> io:format("this outputs two Erlang terms: ~w ~w~n", [hello, world]).
this outputs two Erlang terms: hello world
ok

format/2 (2 表示兩個(gè)參數(shù))接受兩個(gè)列表作為參數(shù)。一般情況下,第一個(gè)參數(shù)是一個(gè)字符串(前面已經(jīng)說(shuō)明,字符串也是列表)。除了 ~w 會(huì)按順序被替換為第二個(gè)列表中的的項(xiàng)以外,第一個(gè)參數(shù)會(huì)被直接輸出。每個(gè) ~n 都會(huì)導(dǎo)致輸出換行。如果正常輸出,io:formate/2 函數(shù)會(huì)返回個(gè)原子值 ok。與其它 Erlang 函數(shù)一樣,如果發(fā)生錯(cuò)誤會(huì)直接導(dǎo)致函數(shù)崩潰。這并 Erlang 系統(tǒng)中的錯(cuò)誤,而是經(jīng)過(guò)深思熟慮后的一種策略。稍后會(huì)看到,Erlang 有著非常完善的錯(cuò)誤處理機(jī)制來(lái)處理這些錯(cuò)誤。如果要練習(xí),想讓 io:format 崩潰并不是什么難事兒。不過(guò),請(qǐng)注意,io:format 函數(shù)崩潰并不是說(shuō) Erlang shell 本身崩潰了。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)