case lets you test a value against a set of patterns, executes the code associated with the first one that matches, and returns the value of that code. The patterns may include guard clauses.

For example, the function returns a two-element tuple. If the open is successful, it returns {:ok, file}, where file is an identifier for the open file. If the open fails, it returns {:error, reason}. We can use case to take the appropriate action when we open a file. (In this case the code opens its own source file.)

case​​"case.ex"​) ​do
{ :ok, file } ->
IO.puts ​"First line: #{, :line)}"
{ :error, reason } ->
IO.puts ​"Failed to open file: #{reason}"


First line: case"case.ex") ...

Get Programming Elixir now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.