【问题标题】:How to concat upcoming string and until new line occurs?如何连接即将到来的字符串并直到出现新行?
【发布时间】:2015-10-27 02:06:50
【问题描述】:

我正在使用从我的设备切碎的比特流返回的elixir_serial,我怎样才能将它连接到长生不老药中,直到在"\n" 分隔符中?我在 node.js node-serialport 中找到了示例,但在我的 handle_info() 中找不到构建它的好示例?

def init([]) do
  {:ok, serial} = Serial.start_link
  Serial.open(serial, "/dev/cu.usbserial-A5026NYN")
  Serial.set_speed(serial, 9600)
  Serial.connect(serial)
  Logger.debug "pid #{inspect serial}"

  # @key_parts = []
  {:ok, []}
end

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

【问题讨论】:

    标签: pattern-matching elixir


    【解决方案1】:

    你可以使用String.split/3:

    iex(1)> String.split("foo\nbar", "\n")
    ["foo", "bar"]
    

    您可以对此进行模式匹配以获取所有数据,直到\n

    iex(2)> [head | _tail] = String.split("foo\nbar", "\n")
    ["foo", "bar"]
    iex(3)> head
    "foo"
    

    如果字符串中没有\n,则原始字符串将在一个包含1个元素的列表中返回。

    编辑

    在收到\n 之前建立一个列表:

    def init(_) do
      {:ok, []}
    end
    
    def handle_info({:elixir_serial, serial, "\n"}, state) do
      #Do stuff with state - be sure to reverse state as we have been building up using `[head | tail]`
      # You can use Enum.reverse(state) for this.
      {:noreply, state}
    end
    
    def handle_info({:elixir_serial, serial, data}, state) do
      {:noreply, [data | state]}
    end
    

    【讨论】:

    • 谢谢,但是如何在实例数组中推送处理的data,如果data 仅包含'\n'字符串,则返回连接数组并将其清空,我不知道该怎么做在长生不老药中?
    • 如何在init()方法中设置实例数组?
    • 你没有“实例”数组的概念——你可以在你的 GenServer 中存储状态——它是第二个参数。状态最初设置为init 函数的返回值{:ok, state} - 所以你可以用{:ok, []} 设置它
    • 再次感谢,模式匹配是一个非常好的功能,你能告诉我如何匹配状态字符串直到 12 个字符吗?
    • @luzny 你可以在警卫中使用byte_sizeelixir-lang.org/getting-started/case-cond-and-if.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    相关资源
    最近更新 更多