Binary pattern matching
You might be familiar with the most popular form of Elixir pattern matching involving tuples:
iex > {:ok, x} = {:ok, 1000}
{:ok, 1000}
iex > x
1000
You can also pattern match binaries:
iex > <<1, y, 2>> = <<1, 255, 2>>
<<1, 255, 2>>
iex > y
255
This gets powerful when you're able to match binary formats.
iex > <<x :: binary-1, y :: binary-2, z :: binary>> = <<1, 255, 254, 2>>
<<1, 255, 254, 2>>
iex > x
<<1>>
iex > y
<<255, 254>>
iex > z
<<2>>
Here's an article about using binary pattern matching to parse a png file.
Tweet