gpt4 book ai didi

erlang - 如何在脚本程序中获取程序名称?

转载 作者:行者123 更新时间:2023-12-02 03:20:53 25 4
gpt4 key购买 nike

我有一个 Erlang 程序,打算使用 escript 运行:

% filename: myscript.erl
-export([main/1]).

main(Args) ->
io:format("Args: ~p~n", [Args]).

当我运行escript myscript.erl 123 456时,会打印以下内容:

Args: ["123","456"]

这很好,但是程序的名称在哪里(即 myscript.erl)?

在 C 中,例如,在 int main(int argc, char *argv[]) { ... } 中,argv[0] 始终包含名称的程序。在 Erlang 中如何获取程序的名称?

最佳答案

来自 erlang escript docs :

To retrieve the pathname of the script, call escript:script_name() from your script (the pathname is usually, but not always, absolute).

这是在行动:

myescript.erl:

-export([main/1]).

main(Args) ->
io:format("Args: ~p~n~p~n", [Args, escript:script_name()]).

在 bash shell 中:

~/erlang_programs$ escript myescript.erl 123 456
Args: ["123","456"]
"myescript.erl"

和:

~/erlang_programs$ cd

~$ escript erlang_programs/myescript.erl 123 456
Args: ["123","456"]
"erlang_programs/myescript.erl"

因此,不管文档怎么说,我都会得到一个相对于我发出 escript 命令的目录的路径,或者等效于我提供给 escript 的路径命令。

Why is the pathname surrounded by double quotes? How can it be removed?

在erlang中,术语“a”是列表[97]的简写符号。同样,术语“erlang_programs/myescript.erl”是列表[101, 114, ...108] 的简写。每次看到 shell 打印出带有双引号的内容时,您都必须对自己重复一遍。事实上,shell 输出双引号字符串而不是它们真正代表的列表,这是 shell 的一个可怕的特性,并且会给初学者和经验丰富的使用者带来难以言表的困惑。 “嘿,让我们打印出该学生在最近三项测试中的原始分数,即 [97,98,99]:

9> io:format("Student scores: ~p~n", [[97,98,99]]).
Student scores: "abc"
ok

什么鬼?!

以下是删除输出引号的一些方法:

1) 使用io:format/2输出时,可以使用控制序列~s:

s: Prints the argument with the string syntax. The argument is ... an iolist(), a binary(), or an atom()... The characters are printed without quotes.

例如:

1> io:format("~s~n", ["hello"]).
hello
ok

2>

(感谢评论中那个操作!)

2) 您可以将列表(例如“abc”)转换为原子:

~$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V9.3 (abort with ^G)

1> list_to_atom("a").
a

2> list_to_atom([97]).
a

3> "a" =:= [97].
true

关于erlang - 如何在脚本程序中获取程序名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54847821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com