从外部erlang文件获取shell中的返回值

时间:2012-05-06 18:17:38

标签: shell erlang

我在erlang中有一个启动某些模块的脚本文件。在erlang shell中,我想使用start函数中返回的对象。

我有我的档案:

-module(myfile).
main() ->
    %% do some operations
    MyReturnVar.

我想让最终用户操作MyReturnVar变量的最简单方法。在shell脚本中,我执行$ erl -s myfile main来执行shell中的函数。

有没有办法在shell中获取MyReturnVar?

另一种方法是直接从shell加载模块

$ erl
1> X = myfile:main().

但是我不太喜欢这个解决方案,我想要一个更“一个命令”的选项(或者我可以在shell脚本中连续使用几个)。

谢谢

3 个答案:

答案 0 :(得分:1)

当你连续说几句时,听起来你想把一个命令的结果输入到另一个命令中。为此你不使用返回值,它只能是一个int,但你使用stdin和stdout。意思是你想要的是将MyReturnVar打印到标准输出。为此你有io:格式。根据值MyReturnVar的类型,您可以执行以下操作:

-module(myfile).
main() ->
    %% do some operations
    io:format("~w", [MyReturnVar]),
    MyReturnVar.

现在,您应该能够将命令的结果传递给其他进程。例如:

$ erl -s myfile main | cat

答案 1 :(得分:0)

您可以(ab)使用.erlang文件来实现此目的(请参阅erl(1)手册页)。或者在erlang-history中进行黑客攻击

答案 2 :(得分:0)

如果可能,请使用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,以便您可以使用管道或只是捕获$?来自shell脚本。

相关问题