模式匹配中byte_size的语法是什么? [英] What is syntax for byte_size in pattern matching?

查看:123
本文介绍了模式匹配中byte_size的语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何匹配以及在 handle_info()中检查 byte_size 等于12长度的模式是什么?我可以在 handle_info()中使用这两种模式吗?第一个将检查字符串以查找新行,第二个将使用 byte_size

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?

不带的示例代码byte_size 模式:

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


推荐答案

是的,您可以同时使用两种模式,这是拥有多个功能子句的目的。

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.

您可以使用不同的二进制模式来匹配12个字节,具体取决于所需的输出:

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

有关可用类型的更多信息和修饰符,您可以查找位字符串语法在线或在 iex 中,通过键入 h<<<>

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 <<>>.

您也可以将保护子句与 byte_size 一起使用:

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

这篇关于模式匹配中byte_size的语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆