← All Articles

How to Read from stdin in Elixir

Posted on

Elixir is rather easy - as long as you get past the pattern matching barrier I stumpled into when writing about how to read program arguments.

The solution to this one was found on Elixir Sips though (you should really check that out, if you want to learn about elixir).

defmodule Reader do
  def read do
    case IO.read(:stdio, :line) do
      :eof -> :ok
      {:error, reason} -> IO.puts "Error: #{reason}"
      data ->
        IO.write(:stdio, data)
        read
    end
  end
end

Reader.read

Run it by calling elixir stdin.exs < stdin.exs and it will echo the source code back to you.

polyglotbitselixirread-from-stdin