LYSE-模块

模块概述

模块是某类函数的集合,放置在同一个文件中。

Erlang中所有函数都必须定义在模块中。

erlang是一个特殊的模块,它会被自动导入。

访问模块中的函数的语法为:模块:函数(参数)

模块声明

编写模块时,声明了两类东西:函数、属性。

属性是模块的元数据。描述模块名称、暴露的函数、作者名字等。

属性的声明语法:-名称(值).

必须声明的属性只有一个:

  -module(name).

需要导出函数时:

  -export([函数1/参数个数, 函数2/参数个数, ..., 函数N/参数个数]).

函数

声明语法:名称(参数) -> 函数体.

函数体由多个表达式组成,","分隔。

最后一个表达式的值就是函数的返回值。

%% Shows greetings.
%% io:format/1 is the standard function used to output text.
hello() ->
io:format("Hello, world!~n").

导入库

语法:-import(模块, [函数1/参数个数, 函数2/参数个数, ..., 函数N/参数个数]).

导入库可能会让函数调用产生歧义,一般只导入lists模块的函数,因为这些函数使用率非常高。

模块文件名和模块名一致,后缀名为".erl"。

定义语法:-define(宏,定义)

使用语法:?宏

编译代码

命令行编译语句:erlc 选项 源文件

模块或shell中的编译语句:compile:file(文件名)

shell中的编译语句:c(模块名)

1> cd("/path/to/where/you/saved/the-module/").
"Path Name to the directory you are in"
ok
2> c(useless).
{ok,useless}

编译后生成".beam"文件。

编译选项

7> compile:file(useless, [debug_info, export_all]).
{ok,useless}
8> c(useless, [debug_info, export_all]).
{ok,useless}

获取模块元数据

9> useless:module_info().
[{exports,[{add,2},
{hello,0},
{greet_and_add_two,1},
{module_info,0},
{module_info,1}]},
{imports,[]},
{attributes,[{vsn,[174839656007867314473085021121413256129]}]},
{compile,[{options,[]},
{version,"4.6.2"},
{time,{2009,9,9,22,15,50}},
{source,"/home/ferd/learn-you-some-erlang/useless.erl"}]}]
10> useless:module_info(attributes).
[{vsn,[174839656007867314473085021121413256129]}]

vsn属性是自动生成的唯一值,标识代码的不同版本(不包括注释)。

用于代码的热加载。

也可以自己定义vsn的值:-vsn(值)

原文地址:https://www.cnblogs.com/sqxy110/p/4996472.html