index

## Tips for Binary Pattern Matching¶

elixir-lang.org tutorial

documentation

Use ? for character identity

In :
?a

Out:
97
In :
<<98>> == <<?b>>

Out:
true
In :
<<?g, ?o, ?\n>> == "go
"

Out:
true

Quotes can also be used

In :
<<"a">> == <<?a>>

Out:
true
In :
<<"[", x :: utf8, "]">> = "[a]"
<<x>>

Out:
"a"

A match group without a known length can only come at the end of a pattern

In :
<<num :: size(16), rest::binary>> = <<1, 0, ?a, ?b, ?c>>
{num, rest}

Out:
{256, "abc"}
In :
<<line :: binary, ?\n>> = "this will not work
"

** (CompileError) "nofile":1 "a binary field without size is only allowed at the end of a binary pattern"


<> is allowed in matches

In :
"foo" <> rest = "foobar"
rest

Out:
"bar"

binary-size and unit(8)-size mean different things

In :
<<x :: binary-size(5)>> = "frail"
x

Out:
"frail"
In :
<<x :: unit(8)-size(5)>> = "frail"
x

Out:
440005650796

Matching length and resusing later in a pattern is useful

In :
<<len :: size(2), msg :: size(len)>> = <<0b1001 :: size(4)>>
msg

Out:
1
In :
# also works in reverse order
<<msg :: size(len), len :: size(2)>> = <<0b1010 :: size(4)>>
msg

Out:
2
In :
# Can only be passed as part of the binary itself
{hlen, blen, <<header :: binary-size(hlen), body :: binary-size(blen)>>} = {4, 4, "headbody"}

** (CompileError) "nofile":1 "variable hlen@1 is unbound"

In :
# or as a previously bound variable
{hlen, blen} = {4, 4}

{"head", "body"}