Erlang:如何将路径字符串传递给函数?

hgb9j2n6  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(177)

我根据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行)

我做错了什么?

vbkedwbf

vbkedwbf1#

filePath is an atom--not a variable:

7> is_atom(filePath).
true

In erlang, variables start with a capital letter. The only way erlang could match your function clause would be to call the function like this:

appender_server:start_link(filePath)

Here is an example:

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

In the shell:

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>

相关问题