Search code examples
elixir

Elixir standard input and standard output


Still a newbie in Elixir. My understanding so far was that we consume standard input with input = IO.read(:stdio,:line) and write a line to standard output with IO.puts(line). Now I found in elexir hexdocs the following example for producing on stdout an upper case version of stdin:

stream = IO.stream(:stdio, :line)
for line <- stream, into: stream do
  String.upcase(line) <> "\n"
end

Here is my partial understanding of this code: The first line tells us that stream is a Stream representing all of stdin. This is an Enumerable, so the comprehension for line <- stream produces successively the individual lines.

What puzzles me is the into: stream clause. This means that the same stdin stream defined above is now used as Collector, and I don't see anything which would actually put something to stdout (no IO.puts).

Does stream somehow mysteriously represents both stdin and stdout in conjunction?


Solution

  • Yes, your analysis is correct (that is why is is named :stdio and not :stdin or :stdout). To check that, you have to start from IO documentation ("Elixir provides :stdio and :stderr as shortcuts to Erlang's :standard_io and :standard_error.") to the Erlang io documentation ("By default all I/O sent to standard_io will en up in the user I/O device of the node that spawned the calling process. ")