Hello World #

一、交互式Hello World #

1.1 启动Shell #

bash
erl

1.2 输出Hello World #

erlang
1> io:format("Hello, World!~n").
Hello, World!
ok

io:format/1 函数返回 ok,这是Erlang中表示成功的原子。

1.3 理解返回值 #

在Erlang中,每个表达式都有返回值:

erlang
1> Result = io:format("Hello~n").
Hello
ok
2> Result.
ok

1.4 格式化输出 #

erlang
1> io:format("Hello, ~s!~n", ["Erlang"]).
Hello, Erlang!
ok
2> io:format("Number: ~p~n", [42]).
Number: 42
ok

常用格式符:

格式符 说明
~s 字符串
~p 美化打印
~w 原样输出
~n 换行
~t 制表符

二、模块文件 #

2.1 创建模块 #

创建 hello.erl 文件:

erlang
-module(hello).
-export([world/0]).

world() ->
    io:format("Hello, World!~n").

2.2 模块结构说明 #

erlang
-module(hello).
  • 声明模块名,必须与文件名相同
erlang
-export([world/0]).
  • 导出函数列表,world/0 表示名为world、参数个数为0的函数
erlang
world() ->
    io:format("Hello, World!~n").
  • 函数定义,函数体以句号结尾

2.3 编译模块 #

在Shell中编译:

erlang
1> c(hello).
{ok, hello}

或使用命令行:

bash
erlc hello.erl

2.4 调用函数 #

erlang
2> hello:world().
Hello, World!
ok

三、脚本模式 #

3.1 使用escript #

创建 hello.erl 文件:

erlang
#!/usr/bin/env escript
main(_Args) ->
    io:format("Hello, World!~n").

3.2 运行脚本 #

bash
chmod +x hello.erl
./hello.erl

或:

bash
escript hello.erl

3.3 带参数的脚本 #

erlang
#!/usr/bin/env escript
main([Name]) ->
    io:format("Hello, ~s!~n", [Name]);
main([]) ->
    io:format("Hello, World!~n").

运行:

bash
./hello.erl Erlang
Hello, Erlang!

四、完整示例 #

4.1 数学运算模块 #

创建 math_demo.erl

erlang
-module(math_demo).
-export([add/2, subtract/2, multiply/2, divide/2]).

add(A, B) ->
    A + B.

subtract(A, B) ->
    A - B.

multiply(A, B) ->
    A * B.

divide(A, B) when B =/= 0 ->
    A / B;
divide(_A, 0) ->
    {error, division_by_zero}.

编译并使用:

erlang
1> c(math_demo).
{ok, math_demo}
2> math_demo:add(10, 20).
30
3> math_demo:subtract(10, 5).
5
4> math_demo:multiply(3, 4).
12
5> math_demo:divide(10, 2).
5.0
6> math_demo:divide(10, 0).
{error,division_by_zero}

4.2 递归函数 #

创建 recursive.erl

erlang
-module(recursive).
-export([factorial/1, fibonacci/1]).

factorial(0) -> 1;
factorial(N) when N > 0 -> N * factorial(N - 1).

fibonacci(0) -> 0;
fibonacci(1) -> 1;
fibonacci(N) when N > 1 -> 
    fibonacci(N - 1) + fibonacci(N - 2).

使用:

erlang
1> c(recursive).
{ok, recursive}
2> recursive:factorial(5).
120
3> recursive:fibonacci(10).
55

五、模块属性 #

5.1 常用属性 #

erlang
-module(example).
-author('developer@example.com').
-vsn("1.0.0").
-export([func/1]).

func(X) -> X.

5.2 自定义属性 #

erlang
-module(custom_attr).
-export([info/0]).

-define(VERSION, "1.0.0").
-author('developer@example.com').

info() ->
    io:format("Version: ~s~n", [?VERSION]),
    io:format("Author: ~p~n", [?MODULE:module_info(attributes)]).

5.3 查看模块信息 #

erlang
1> c(custom_attr).
{ok, custom_attr}
2> custom_attr:module_info().
[{module,custom_attr},
 {exports,[{info,0},{module_info,0},{module_info,1}]},
 {attributes,[{vsn,[...]}]},
 {compile,[...]},
 {native,false},
 {md5,...}]

六、编译选项 #

6.1 在Shell中编译 #

erlang
1> c(hello, [debug_info]).
{ok, hello}
2> c(hello, [export_all]).
{ok, hello}
3> c(hello, [{outdir, "ebin"}]).
{ok, hello}

6.2 常用编译选项 #

选项 说明
debug_info 包含调试信息
export_all 导出所有函数
{outdir, Dir} 指定输出目录
{i, Dir} 添加包含目录
{d, Macro} 定义宏
warnings_as_errors 警告视为错误

6.3 编译器指令 #

erlang
-module(compile_directives).
-compile([debug_info, export_all]).
-compile({nowarn_unused_function}).

unused_function() ->
    ok.

七、注释与文档 #

7.1 注释 #

erlang
-module(comments).
-export([func/1]).

func(X) ->
    X + 1.

7.2 文档注释(Edoc) #

erlang
-module(edoc_example).
-export([add/2]).

add(A, B) ->
    A + B.

生成文档:

bash
erl -noshell -eval "edoc:application(example, \".\", [{dir, \"doc\"}])" -s init stop

八、错误处理 #

8.1 编译错误 #

erlang
-module(error_example).
-export([broken/0]).

broken() ->
    missing_end

错误信息:

text
error_example.erl:5: syntax error before: end of file

8.2 运行时错误 #

erlang
1> 1 / 0.
** exception error: bad argument in an arithmetic expression
     in operator  '/'/2
        called as 1 / 0

8.3 函数未定义 #

erlang
1> unknown:func().
** exception error: undefined function unknown:func/0

8.4 模式匹配失败 #

erlang
1> {a, b} = {x, y}.
** exception error: no match of right hand side value {x,y}

九、调试技巧 #

9.1 使用io:format调试 #

erlang
debug_func(X) ->
    io:format("X = ~p~n", [X]),
    Result = X * 2,
    io:format("Result = ~p~n", [Result]),
    Result.

9.2 使用dbg模块 #

erlang
1> dbg:tracer().
{ok,<0.89.0>}
2> dbg:p(all, c).
{ok,[{matched,nonode@nohost,26}]}
3> dbg:tpl(math_demo, add, x).
{ok,[{matched,nonode@nohost,1},{saved,x}]}
4> math_demo:add(1, 2).
(<0.80.0>) call math_demo:add(1,2)
30

9.3 使用debugger #

erlang
1> debugger:start().

十、项目结构 #

10.1 简单项目 #

text
simple_project/
├── src/
│   └── main.erl
└── ebin/

10.2 标准OTP项目 #

text
otp_project/
├── src/
│   ├── myapp.app.src
│   ├── myapp_app.erl
│   └── myapp_sup.erl
├── ebin/
├── include/
├── priv/
└── test/

10.3 使用Rebar3 #

bash
rebar3 new app myapp
cd myapp
rebar3 compile
rebar3 shell

十一、总结 #

本章学习了:

  • 交互式编程(Erlang Shell)
  • 模块文件(.erl)
  • 脚本模式(escript)
  • 模块属性和导出
  • 编译和运行
  • 基本调试技巧

准备好学习Erlang语法基础了吗?让我们进入下一章。

最后更新:2026-03-27