Today I Learned

hashrocket A Hashrocket project

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.

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.