io:format and output

Every program prints something, and in Erlang the function that prints is io:format/2: a format string with tilde directives and a list of terms. The same format language appears in three places, and the differences matter: io:format writes to a device, io_lib:format builds the text without writing it, and io:put_chars writes its argument as it is, with no directives at all.

Format strings

A tilde starts a control sequence. ~p prints any term readably, ~s prints a string without its quotes, ~w prints a term in the standard syntax, ~b prints an integer in decimal, ~B takes a base after the dot, ~f prints a float with the precision after the dot, ~c prints one character, and ~n is the newline. The program below runs each of them:

report.erl

-module(report). -export([main/0]). main() -> io:format("~p~n", ["world"]), io:format("~s~n", ["world"]), io:format("~.2f~n", [3.14159]), io:format("~c ~b ~.16B~n", [$A, 255, 255]), table([{1, "buy milk", false}, {2, "call Ada", true}]). table(Rows) -> io:format("~-3s ~-10s ~s~n", ["#", "task", "done"]), lists:foreach(fun row/1, Rows). row({Number, Task, Done}) -> io:format("~-3b ~-10s ~s~n", [Number, Task, marker(Done)]). marker(true) -> "yes"; marker(false) -> "no".

erlc report.erl

erl -noshell -eval 'report:main(), halt().'

"world" world 3.14 A 255 FF # task done 1 buy milk no 2 call Ada yes

The first two lines are the difference that bites: ~p keeps the quotes around a string because it prints the term, and ~s prints the characters. ~p is the debugging choice, and ~s is for text a user reads. ~.2f rounds to two decimals, and ~.16B prints 255 in base sixteen.

Widths and a table

A number before the letter is the field width, and a minus sign aligns the value to the left. That is all a plain text table needs, and it is what the last three lines of the run above show: ~-3s pads the header to three characters from the right, ~-10s pads a task to ten, and ~-3b pads a number. The width counts characters for a proper Unicode string: a binary printed with ~ts on a device in unicode mode keeps its columns aligned, which is the difference the encodings lesson explains.

~p and ~w

~p and ~w print the same term, and ~p breaks it over several lines when it is too wide for the device, while ~w keeps one line whatever its length. A log line that must stay one line uses ~w; a term a person reads uses ~p. The two prints in the program above differ only in that choice, and the difference is visible in the run.

io_lib

io_lib:format/2 builds the same text without printing it. The answer is a deep list, which is exactly what file:write_file/2, gen_tcp:send/2 and an HTTP header want, and lists:flatten/1 turns it into a plain string when a function insists on one. This program shows the deep list, the flattened string, and a line written to a file:

lib_format.erl

-module(lib_format). -export([main/0]). main() -> Deep = io_lib:format("~p", [{ok, 1}]), io:format("deep: ~p~n", [Deep]), Flat = lists:flatten(Deep), io:format("flat: ~p~n", [Flat]), Line = io_lib:format("task ~s: ~p~n", ["buy milk", done]), ok = file:write_file("log.txt", Line), {ok, Written} = file:read_file("log.txt"), io:format("file: ~p~n", [Written]).

erlc lib_format.erl

erl -noshell -eval 'lib_format:main(), halt().'

deep: [[123,["ok",44,"1"],125]] flat: "{ok,1}" file: <<"task buy milk: done\n">>

The deep list holds numbers for the punctuation and binaries or strings for the text, and it is the shape an IO list is defined as. Nothing touches the console, so the function that builds a log line, a JSON fragment or a header is easy to test: it takes values and answers bytes. The term formats lesson uses the same list for a file of terms.

A format that does not fit

The directives are checked at run time against the arguments, and a mismatch raises badarg in the process that prints. It is not a compile error: the format string is a value, and the compiler does not read it. The program below passes an integer to ~s and catches the error:

bad_format.erl

-module(bad_format). -export([main/0]). main() -> Result = try io:format("~s~n", [123]) of ok -> ok catch error:Reason -> {error, Reason} end, io:format("result: ~p~n", [Result]).

erlc bad_format.erl

erl -noshell -eval 'bad_format:main(), halt().'

result: {error,badarg}

The mistake is easy to make in a server: a log line with ~s and a binary where a string was expected raises in the process that logs, and a crash report about printing replaces the message that was being printed. ~ts takes a unicode binary, ~p takes anything, and a format string that must not fail is worth a test of its own.

Raw text

io:put_chars/1 writes its argument as it is, with no format string and no tilde codes. It takes an iolist, so a program that already built bytes writes them without a copy. A ~n inside its argument stays two characters, which is the trap the program shows:

raw.erl

-module(raw). -export([main/0]). main() -> io:put_chars("raw text~n"), io:put_chars("\n"), Data = [<<"a ">>, "mixed ", <<"iolist">>, "\n"], io:put_chars(Data), io:format("bytes: ~p~n", [iolist_size(Data)]).

erlc raw.erl

erl -noshell -eval 'raw:main(), halt().'

raw text~n a mixed iolist bytes: 15

The first line is the trap: the tilde and the n are text, because put_chars interprets nothing. The third call writes a list that mixes binaries and strings, which is the shape most of the standard library answers, and iolist_size/1 counts the bytes without building them. Every printing function also takes the device as an optional first argument: io:format(standard_error, "~p~n", [Term]) writes to standard error, and an open file handle is a device too, which is how a program logs into a file with the file module.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the ~p control sequence print?

    Answer

    A term readably, with quotes around strings

    ~p is the readable form of any term, so strings keep their quotes.

  2. How do ~p and ~s differ for a string?

    Answer

    ~p keeps the quotes, ~s drops them

    ~p shows the value as Erlang source, ~s prints the characters themselves.

  3. What does ~.2f do to a float?

    Answer

    Rounds it to two decimals

    The dot introduces the precision, so 3.14159 prints as 3.14.

  4. What does ~-10s do?

    Answer

    Left aligns in ten characters

    The number is the field width and the minus sign moves the value to the left.

  5. What does this module print? -module(q4). -export([main/0]). main() -> Text = io_lib:format("~s=~b", ["count", 3]), Flat = lists:flatten(Text), io:format("~p ~p~n", [Flat, iolist_size(Text)]).

    Answer

    "count=3" 7

    The flattened text is the string count=3, and its seven bytes are what the iolist size counts.

  6. What does io_lib:format/2 return?

    Answer

    A deep list of the formatted text

    It builds the text and hands it back as a deep list, ready for a writer.

  7. What does this module print? -module(q1). -export([main/0]). main() -> io:format("~p|~s~n", ["hi", "hi"]).

    Answer

    "hi"|hi

    The readable form keeps the quotes and the string form drops them.

  8. What does this module print? -module(q2). -export([main/0]). main() -> io:format("~.1f ~.16B ~c~n", [2.25, 31, $A]).

    Answer

    2.3 1F A

    One decimal rounds 2.25 to 2.2, base sixteen writes 31 as 1F, and $A is the character.

  9. What does this module print? -module(q3). -export([main/0]). main() -> R = try io:format("~b~n", ["text"]) of ok -> ok catch error:Reason -> {error, Reason} end, io:format("~p~n", [R]).

    Answer

    {error,badarg}

    A string is not an integer, so the directive and the argument disagree and the call raises badarg.

  10. Why does io:put_chars("raw~n") print the tilde and the n?

    Answer

    put_chars takes no format string

    put_chars writes the argument verbatim; only the format functions interpret tilde codes.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev