我在erlang中有一个脚本文件,可以启动一些模块。在 erlang shell 中,我想使用从 start 函数返回的对象。
我有我的文件:
-module(myfile).
main() ->
%% do some operations
MyReturnVar.
我希望最终用户拥有最简单的方法来操作MyReturnVar
变量。在 shell 脚本中,我执行$ erl -s myfile main
shell 中的函数。
有没有办法让 MyReturnVar 在 shell 中?
另一种方法是直接从外壳加载模块
$ erl
1> X = myfile:main().
但我不太喜欢这个解决方案,我想要一个更"一个命令"的选项(或者我可以在 shell 脚本中连续执行几个命令)。
谢谢
当你连续说几个时,听起来你想将一个命令的结果传送到另一个命令中。为此,您不使用返回值,该值只能是 int,但使用 stdin 和 stdout。这意味着您想要的是打印MyReturnVar
到标准输出。为此,你有io:format。根据MyReturnVar
的值类型,您可以执行以下操作:
-module(myfile).
main() ->
%% do some operations
io:format("~w", [MyReturnVar]),
MyReturnVar.
现在,您应该能够通过管道将命令的结果传送到其他进程。前任:
$ erl -s myfile main | cat
您可以使用 .erlang
文件来实现此目的(请参见erl(1)
手册页)。或者在二郎历史中四处闲逛.
如果可能,请使用 escript。
$cat test.escript
#!/usr/local/bin/escript
main([]) ->
MyReturnVar=1,
io:format("~w", [MyReturnVar]),
halt(MyReturnVar).
$escript test.escript
1
$echo $?
1
这将打印出 MyReturnVar 并返回 MyReturnVar,以便您可以与 pipe 一起使用,或者只是从 shell 脚本中捕获 $?