Module的Attribute形式如下:
-Attr(Value).
其中Attr为atom,Value可以为任何直接的term。
Attribute包含预定义的Attributes以及用户自定义的Attributes。
预定义模块Attribute(Pre-Defined Module Attributes):
-module(Module)
名为Module的模块声明,Module为atom,Module必须与此文件文件名相同(除去.erl后缀名,比如module1.erl,则Module为module1)
-export(Functions)
说明本模块导出的函数列表,Functions形式如下[Function1/Artiy1, ..., FunctionN/ArityN],其中FunctionN为atom,ArtityN为integer
-import(Module, Functions)
引入某个模块的函数列表,这样使用Module的函数时,可以像使用本地函数一样,不用指定模块前缀。Functions与export中的 Functions相同,Module为atom。推荐不要使用import,因为容易混淆,而且影响代码自动更新。(这里类似C++中的using namespace std; 这样以后使用stl相关的函数,类时不用添加std::前缀)
-compile(Options)
指定编译选项,具体参考compile文档。在我们写代码时,经常使用-compile(export_all),将本模块中的所有函数导出,这里仅是为了测试代码方便,在最后的产品中,应该尽力减少每个模块导出的函数。
-vsn(Vsn)
模块的版本信息,Vsn为一个字面信息,可以为任何Term。可以通过beam_lib:version/1获取,如果没有指定vsn则默认为Module的checksum
注意:-record,-macro不时模块的属性,尽管它们很像。
用户自定义Attributes(User-Defined Attributes):
-SomeTag(Value)
SomeTag为atom,Value为任何具有直接字面意义的Term。
Attribute的获取
Module的Attributes信息,会在Module被编译的时候添加到beam文件中。因此可以通过 Module:module_info()获取Moudle的整体信息,也可以通过Module:module_info(attributes)获取所有用户自定义的属性信息。也可以通过:beam_lib:chunks("module.beam", [attributes])获取所有用户自定义的属性信息。
让我们写一小段代码,用来方便获取某个属性:
-module(extract).
-export([attribute/2]).
attribute(File, Key) ->
case beam_lib:chunks(File, [attributes]) of
{ok, {_Module, [{attributes, L}]}} ->
case lookup(Key, Key) of
{ok, Value} ->
Value;
error ->
exit(badAttribute)
end;
_ ->
exit(badFile) end.
lookup(Key, [{Key, Val} | _Tail]) -> Val;
lookup(Key, [_H | Tail]) -> lookup(Key, Tail);
lookup(Key, []) -> error.
Update:现在我们已经不需要这个函数了,在R12B中,每个Module自动引入了一个module_info函数,我们可以通过其获取Module的各种属性
分享到:
相关推荐
Erlang是一种面向并发、分布式计算的编程语言,它的源代码是组织在模块(module)中的。模块是Erlang程序的基本单位,包含了特性(attribute)和函数(function)声明。下面将详细介绍Erlang模块的规则、特性、...
py 是为 Erlang 生态系统准备... Get object attributes Call builtins and operators with convenient wrappers 在分布式环境中运行 Python 的方法,充分利用 Erlang 的优势,包括容错、可伸缩、并发、实时等特性
Module attributes provide additional metadata about the module. They include: - **`-module(Module)`**: This attribute defines the name of the module and must be specified first. The module name ...
Mnesia.create_table(:my_table, [{:attributes, [:key, :value]}]) ``` 调试 Elixir 提供了 `iex -S mix` 选项启动交互式环境,加载当前项目以便于调试。 守护进程(Poolboy) Poolboy 是一个工作池管理库,用于...
- **模块属性(Module Attributes)**:用于存储元数据和代码中的配置。 - **IEx(Interactive Elixir)**:内置的交互式 shell,便于测试和调试代码。 通过 Elixir 抽认卡,学习者可以逐步掌握这些关键知识点,...