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



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

我做错了什么?

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> 

相关内容

最新更新