What is syntax for byte_size in pattern matching?

≯℡__Kan透↙ 提交于 2019-12-07 05:59:46

问题


How to match and what syntax is to check byte_size equal 12 length pattern in handle_info()? Can I use both patterns in handle_info(), eg. first that will check string for new line, second with byte_size?

Example code without byte_size pattern:

def init(_) do
  {:ok, []}
end

def handle_info({:elixir_serial, serial, "\n"}, state) do
  {:noreply, Enum.reverse(state)}
end

def handle_info({:elixir_serial, serial, data}, state) do
  Logger.debug "data: #{data}"
  {:noreply, [data | state]}
end

回答1:


Yes, you can use both patterns, this is the purpose of having multiple function clauses. From top to bottom, the first matching function clause will be executed.

You can use different binary patterns to match 12 bytes, depending on which output you need:

iex> <<data::bytes-size(12)>> = "abcdefghijkl"
"abcdefghijkl"
iex> data
"abcdefghijkl"

iex> <<data::size(96)>> = "abcdefghijkl"
"abcdefghijkl"
iex> data
30138990049255557934854335340

These patterns can of course be used in your function clauses:

def handle_info({:elixir_serial, serial, <<data::bytes-size(12)>>}, state) do
  # ...
end

def handle_info({:elixir_serial, serial, <<data::size(96)>>}, state) do
  # ...
end

For more info on available types and modifiers, you can look up the documentation of the bitstring syntax online or in iex by typing h <<>>.

You could also use a guard clause together with byte_size:

def handle_info({:elixir_serial, serial, data}, state) when byte_size(data) == 12 do
  # ...
end


来源:https://stackoverflow.com/questions/33352329/what-is-syntax-for-byte-size-in-pattern-matching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!