case

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 File.open 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.)

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

produces:

 
First line: case File.open("case.ex") ...

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.