Functions for handling input and output are provided by the IO
module.
IO.puts/2
writes a string to the standard output, followed by a newline. Returns :ok
.IO.write/2
writes a string to the standard output, without adding a newline. Returns :ok
.IO.gets/2
reads a line from the standard input.IO.inspect/2
writes anything to the standard output, accepts useful options like :label
. Returns the value it was passed unchanged. Useful for debugging.String.Chars
protocolIf you try to pass to IO.puts/2
a value that it cannot print, you will see a Protocol.UndefinedError
error.
IO.puts({:ok, 7})
# ** (Protocol.UndefinedError) protocol String.Chars not implemented for {:ok, 7} of type Tuple
When this happens, you might want to use IO.inspect/2
instead.
IO.inspect/2
for debuggingIO.inspect/2
is perfect for debugging because it returns its argument unchanged, it can print anything, and it offers a :label
option.
"HELLO\n"
|> String.trim()
|> IO.inspect(label: "step 1")
|> String.downcase()
|> IO.inspect(label: "step 2")
# > step 1: "HELLO"
# > step 2: "hello"
# => "hello"
The first argument to all those functions is an IO device, with the default value of :stdio
(standard input/output). To write to the standard error device, use :stderr
instead. An IO device could also be a process, for example one created by calling File.open/2
, which would allow writing to a file.