版权声明:@潘广宇博客, https://blog.csdn.net/panguangyuu/article/details/89069185
第2章 Erlang速览
2.1 Shell
① 每一条表达式都必须以一个句号 + 一个空白字符(空格、制表符、回车符)结尾,如 1 + 2.
2.1.1 = 操作符
① Erlang 是函数式语言,一旦定义 X = 123,X 永远就是 123,不允许改变!
2.1.2 变量和原子的语法
变量:大写字母开头,如:X、A_long_name
原子:小写字母开头,是符号常量,如:monday
2.2.1 在 shell 里运行 Hello World
-module(hello).
-export([start/0]).
start() -> io.format("hello, world ~n").
% 启动 Erlang shell
> erl
> c(hello). % 编译 hello.erl 代码
{ok, hello} % 表示编译成功
> hello:start(). % 调用 hello 模块的 start 函数
2.2.2 在 Erlang shell 外编译
erlc hello.c % 编译并生成 hello.beam
erl -noshell -s hello start -s init stop
% 调用 hello:start() 函数,然后调用 init:stop() 函数终止会话
2.3.1 文件服务器进程
文件服务器 file_server.erl
-module(file_server).
-export([start/1, loop/1]).
start(Dir) -> spawn(file_server, loop, [Dir]).
loop(Dir) ->
receive
{Client, list_dir} ->
Client ! {self(), file:list_dir(Dir)};
{Client, {get_file, File}} ->
Full = filename:join(Dir, File),
Client ! {self(), file:read_file(Full)}
end,
loop(Dir). % 无限循环写法。
% 在erlang中,进程标识符类似 <0.47.0>
文件客户端 file_client.erl
-module(file_client).
-export([ls/1, get_file/2]).
ls(Server) ->
Server ! {self(), list_dir},
receive
{Server, FileList} -> FileList
end.
get_file(Server, File) ->
Server ! {self(), {get_file, File}},
receive
{Server, Content} -> Content
end.