Elixir:未使用的变量名(尽管已使用)

时间:2019-02-08 13:58:52

标签: elixir

 def build_map(script_str) do
    script_str = String.replace_leading(script_str ")", "")
    script_str = String.replace(script_str, "false", "111")
    script_str = String.replace(script_str, "null", "111")
    script_str = String.replace(script_str, "\'", "111")
    String.replace(script_str, ")", "")
end

通过混合命令iex -S mix打开交互式外壳会出现以下错误:

Compiling 1 file (.ex)
warning: variable "script_str" is unused
  lib/moviematch.ex:21


== Compilation error in file lib/moviematch.ex ==
** (CompileError) lib/moviematch.ex:22: undefined function script_str/2
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:680: :erl_eval.do_apply/6

我不老长生不老药,有人可以帮我这个忙。

2 个答案:

答案 0 :(得分:2)

为了格式化,将其发布为答案。 请不要投票。

整个函数体不是Elixir惯用代码。这就是我们使用Kernel.|>/2又名管道运算符 在Elixir中编写此代码的方法

def build_map(script_str) do
  script_str
  |> String.replace_leading(")", "")
  |> String.replace("false", "111")
  |> String.replace("null", "111")
  |> String.replace("\'", "111")
  |> String.replace(")", "")
end

这样,您犯错误的机会就更少了。

答案 1 :(得分:1)

函数的第一行出现错误。 Elixir尝试执行script_str ")",但是找不到script_str函数并大声抱怨。

替换此

script_str = String.replace_leading(script_str ")", "")

有了这个

script_str = String.replace_leading(script_str, ")", "")

另外,请参见another answer,并重写了功能代码以使Elixir更加惯用。