Erlang scripting support 让erlang可以向unix script 一样做脚本使用。
script-name script-arg1 script-arg2...escript escript-flags script-name script-arg1 script-arg2...
以下是一个例子
$ chmod u+x factorial
$ cat factorial
#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable -sname factorial -mnesia debug verbose
main([String]) ->
try
N = list_to_integer(String),
F = fac(N),
io:format("factorial ~w = ~w\n", [N,F])
catch
_:_ ->
usage()
end;
main(_) ->
usage().
usage() ->
io:format("usage: factorial integer\n"),
halt(1).
fac(0) -> 1;
fac(N) -> N * fac(N-1).
$ ./factorial 5
factorial 5 = 120
$ ./factorial
usage: factorial integer
$ ./factorial five
usage: factorial integer
escript模块头不同于普通模块。
第一行用于指定解释器,用于解释escript,但是如果你这样调用脚本
$ escript factorial 5
第一行就不起作用了,但是第一行不能包含代码,将不会被执行。
在上面这个例子中,第二行包含一个可选指令使Emacs 编辑器进入编辑erlang源码模式。该指令只能在第二行。
If there is a comment selecting the encoding it can be located on the second line.
The encoding specified by the above mentioned comment applies to the script itself. The encoding of the I/O-server, however, has to be set explicitly like this:
io:setopts([{encoding, unicode}])
The default encoding of the I/O-server for standard_io is latin1 since the script runs in a non-interactive terminal (see Using Unicode in Erlang).
在第三行可能给模拟器一些参数,例如
%%! -smp enable -sname factorial -mnesia debug verbose
参数行必须以 %%!开始,后面的将被解释为模拟器的参数。
如果你知道可执行文件的路径,第一行你直接写路径,如:
#!/usr/local/bin/escript