在Erlangshell中,如何自动读取所有记录定义头

jfgube3f  于 2022-12-08  发布在  Erlang
关注(0)|答案(3)|浏览(115)

一开始是这样一个问题:
几乎每次使用Erlang shell时,我都希望在shell启动时运行一些命令,例如类似于

rr("*.hrl").

或者类似的。现在我每次启动Erlang shell时都要输入它,我已经厌倦了它,并且总是忘记它。

但是这实际上是一个错误的问题!因为我实际上想做的是在每个shell作业中读取我的记录定义头。而不是在启动时运行其他shell内置命令。所以我改变了问题头来显示它应该如何问的问题。

lx0bsm1f

lx0bsm1f1#

在尝试.erlang的解决方案时,我偶然发现了一个针对特定rr/1用法的解决方案:
从shell的联机帮助页中:
在shell中有一些对读取和打印记录的支持。在编译过程中,记录表达式被转换为元组表达式。在运行时,不知道元组是否实际代表记录。编译器使用的记录定义在运行时也不可用。因此,为了在可能的情况下读取记录语法并将元组作为记录打印,记录定义必须由shell自己维护。2用于读取、定义、遗忘、列出和打印记录。请注意,每个作业都有自己的一组记录定义。为了方便起见,记录定义在模块shell_default和user_default中(如果已加载)。例如,将行

-include_lib("kernel/include/file.hrl").

设置为user_default可使shell中的file_info定义变得可用。
为了澄清起见,我补充一些例子:
文件foo.hrl

-record(foo, {bar, baz=5}).

文件:user_default.erl

-module(user_default).
-compile(export_all).

-include("foo.hrl").  % include all relevant record definition headers here

 %% more stuff probably ...

让我们在shell中试用一下:

$ erl
Erlang R13B04 (erts-5.7.5) [source] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.5  (abort with ^G)
1> #foo{}.
#foo{bar = undefined,baz = 5}

→ shell知道来自foo.hrl的记录

jaxagkaj

jaxagkaj2#

The file .erlang is evaluated when the shell is started, but it is NOT evaluated in the context of the shell. This means that it can only contain general expressions which are evaluated and not shell commands. Unfortunately rr() is a shell command (it initialises local shell data to recognise records) so it can not be used in the .erlang file.
While the user defined module user_default , which must be preloaded, can include files which contain record definitions using -include or -include_lib , these record definitions will then only be available to functions defined within user_default . user_default is normal compiled module and exported functions in it are called as any other functions so the record definitions will not be visible within the shell. user_default allows the user to define more complex functions which can be called from within the shell as shell commands.
EDIT:
I was partially wrong here. While I was correct about how .erlang is evaluated and how the functions in user_default are called I missed how user_default.erl is scanned at shell startup for record definitions which are then available within the shell. Thanks @Peer Stritzinger for pointing this out.

9w11ddsr

9w11ddsr3#

将其放在主目录中名为.erlang的文件中(请参见http://www.erlang.org/documentation/doc-5.2/doc/getting_started/getting_started.html中的第1.7.1节)。

相关问题