- 1 year ago
How to cleanly take multiline input from the terminal using Elixir?
Comment
1 / 1
In Elixir, you can take multiline input from the terminal using the IO.gets/1
function in combination with a loop. Here's an example of how you can do it:
elixirdefmodule MultiLineInput do
def read_input() do
read_input([])
end
defp read_input(lines) do
case IO.gets("") do
{:ok, line} ->
case String.trim(line) do
"" -> lines
line -> read_input([line | lines])
end
_ ->
lines
end
end
end
# Usage example
input = MultiLineInput.read_input()
IO.inspect(input)
Here, we define a module MultiLineInput
that provides the read_input/0
function to read multiline input. It uses the IO.gets/1
function to read each line from the terminal. The read_input/1
function recursively reads lines until an empty line is encountered (signifying the end of input) and accumulates them in a list.
You can call MultiLineInput.read_input/0
to start reading multiline input. Once the user finishes entering input (typically by entering an empty line), the function returns the list of lines entered.
Feel free to adapt this code snippet to fit your specific requirements.