【问题标题】:Erlang: How to pass a path string to a function?Erlang:如何将路径字符串传递给函数?
【发布时间】:2021-03-14 17:52:14
【问题描述】:

我根据 OTP gen_server 行为创建了一个新文件。

这是它的开始:

-module(appender_server).
-behaviour(gen_server).

-export([start_link/1, stop/0]).
-export([init/1, handle_call/3, handle_cast/2]).

start_link(filePath) ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, filePath, []).

init(filePath) ->
    {ok, theFile} = file:open(filePath, [append]). % File is created if it does not exist.

...

使用 c(appender_server) 编译好的文件。

当我尝试从 shell 调用 start_link 函数时,如下所示:

appender_server:start_link("c:/temp/file.txt").

我明白了:

** 异常错误:没有函数子句匹配 appender_server:start_link("c:/temp/file.txt") (appender_server.erl, 第 10 行)

我做错了什么?

【问题讨论】:

    标签: erlang erlang-otp


    【解决方案1】:

    filePath 是一个原子——不是一个变量:

    7> is_atom(filePath).
    true
    

    在erlang中,变量以大写字母开头。 erlang 可以匹配您的函数子句的唯一方法是像这样调用函数:

    appender_server:start_link(filePath)
    

    这是一个例子:

    -module(a).
    -compile(export_all).
    
    go(x) -> io:format("Got the atom: x~n");
    go(y) -> io:format("Got the atom: y~n");
    go(X) -> io:format("Got: ~w~n", [X]).
    

    在外壳中:

    3> c(a).
    a.erl:2: Warning: export_all flag enabled - all functions will be exported
    {ok,a}
    
    4> a:go(y).
    Got the atom: y
    ok
    
    5> a:go(x).
    Got the atom: x
    ok
    
    6> a:go(filePath). 
    Got: filePath
    ok
    
    7> a:go([1, 2, 3]).
    Got: [1,2,3]
    ok
    
    8> 
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 2016-01-28
      • 2013-12-11
      相关资源
      最近更新 更多