目录:
1. Erlang安装
2. 开启和停止Erlang shell
3. 配置开发环境
4. 运行程序的几种方法
1. Erlang安装
(1). 二进制发布版(此处不做介绍)(2). 从源代码安装Erlang:$ tar -xzf otp_src_R15B-4.tar.gz 解包 [tar -xzf的意思是解压并解包一个文件,这个文件应该是经tar打包后按gzip格式压缩的。]$ cd otp_src_R15B-4$ ./configure 配置$ make 编译$ sudo make install 安装
2. 开启和停止Erlang shell
开启Erlang:erl停止Erlang:方法一:Ctrl + C (Windows下是Ctrl+Break),然后按下a方法二:erlang:halt().erlang:halt() 是一个内建函数BIF,可以即刻停止系统运行。缺陷:如果你在运行一个大型的数据库程序,轻易地停止运行,那么下次启动系统时,系统将不得不进行一次错误修复。方法三:q().输入此命令,系统会刷新所有开启的文件,如果数据库开启会关闭数据库,按顺序关闭所有的OTP应用程序。q()是init:stop()命令在shell中的别名。
3. 配置开发环境
code:get_path(). 获取当前加载路径code:add_patha(Dir) 增加一个新目录Dir到加载路径的开头code:add_pathz(Dir) 增加一个新目录Dir到加载路径的结尾code:all_loaded(). 返回一个所有已被加载模块的列表常见做法:将这些命令集中到一个名为 .erlang文件中,或使用以下命令开启Erlang:$erl -pa Dir1 -pa Dir2 ... -pz Dirk -pz Dirn ...
4. 运行程序的几种方法
程序:-module(hello).-export([start/1]).start() ->io:format("hello world~n").
方法一:在Erlang shell中编译运行
1> c(hello).{ok,hello}2> hello:start().hello worldok
方法二:在命令提示符下编译运行
$ erlc hello.erl (编译hello.erl文件,生成一个.beam文件)$ erl -noshell -s hello start -s init stophello world注:-noshell 表示启动Erlang,但关闭shell,因此不会看到Erlang的提示信息-s hello start 表示运行hello:start()-s init stop 当apply(hello,start,[]) 运行结束时,执行init:stop()-s 命令由一个apply语句进行编译和运行,可以再erl -noshell ... 命令中运行任意多个-s命令
编写shell脚本执行:在OS命令行执行任意一个Erlang函数,可以使用-eval 参数执行这样的快速脚本:erl -eval 'io:format("Memory ~p~n",[erlang:memory(total)]).' -noshell -s init stop
erl -noshell 命令可以写入一个shell脚本中,因此我们通常会创建一个shell脚本来运行设置路径的程序(使用-pa 目录)并启用它。
例如: hello.sh
#!/bin/sh
#这是一个shell脚本,执行hello的start()
erl -noshell -pa /root/work/myErlangTest\ # 此处必须是包含hello.beam文件的目录的绝对路径
-s hello start -s init stop
执行:
$ chmod u+x hello.sh 更改文件的user权限,添加执行权限
$ ./hello.sh
hello world
方法三:把程序当做escript脚本运行(无需进行编译)
举例:建立下面的文件:#!/usr/bin/env escriptmain(_) ->io:format("hello world ~n").执行:$ chmod u+x hello$ ./hellohello world
方法四:用命令行参数编程(运行带有参数的函数)
举例:fac.erl
-module(fac).-export([fac/1]).fac(0) -> 1;fac(N) -> N * fac(N-1).
这个程序可以在Erlang shell中运行,如果想要在命令行执行,需要将程序修改下,以支持命令行参数。
-module(fac1).-export([ factorial /1]).factorial([A]) ->I = list_to_integer(atom_to_list(A)),F = fac(I),io:format("factorial ~w = ~w~n",[I,F]),init:stop().fac(0) -> 1;fac(N) -> N * fac(N-1).
运行:
$erlc fac1.erl$erl -noshell -s fac1 factorial 5factorial 5 = 120
本文详细介绍了Erlang的安装过程,包括从源代码安装,并讲解了如何开启和停止Erlang shell。接着,文章阐述了如何配置Erlang开发环境,如调整加载路径。此外,还介绍了四种运行Erlang程序的方法,包括在shell中编译运行、命令行编译运行、编写shell脚本和escript脚本运行,以及处理命令行参数的编程方式。

1297

被折叠的 条评论
为什么被折叠?



