erlang 变量存储在哪里,变量在Erlang

I have a very simple Erlang program:

-module(test).

-export([start/0]).

Code = "Z00887".

start() -> io:fwrite(Code).

And I have follows two errors:

c:/erl6.1/dev/test.erl:4: syntax error before: Code

c:/erl6.1/dev/test.erl:5: variable 'Code' is unbound

Could you please help me correctly using variables in my code.

解决方案

You are defining a variable that is global to the module, which is not allowed. Remember, "variables" in Erlang are really "symbols", so there is no concept of a "global" constant across all functions or processes. The closest thing to this in Erlang would be a macro defined in the module, but if a value is only needed in one place and you want to name it then this must be done within the function definition.

Also, do not use io:fwrite/1 or io:format/1. The problem is the possible inclusion of escape characters in the string you are passing. For example, this causes an error: Code = "Wee~!", io:format(Code). and it will not be caught by the compiler.

The most common thing to do is define a variable within the function:

-module(foo).

-export([start/0]).

start() ->

Code = "Z00887",

io:fwrite("~p~n", [Code]).

You could also just use the value directly:

-module(foo).

-export([start/0]).

start() ->

io:fwrite("Z00887~n").

Or you could define a macro across the whole module:

-module(foo).

-export([start/0]).

-define(CODE, "Z00887").

start() ->

io:fwrite("~p~n", [?CODE]).

Or you could even define a stub function that returns what you want:

-module(foo).

-export([start/0]).

start() ->

io:fwrite("~p~n", [code()]).

code() -> "Z00887".

This last version is actually not as weird as it may seem at first. Very often when developing some code early on you will know you need a value somewhere that you will need to derive in some way, but don't want to worry about the details of it just yet. A stub function is an excellent way to hide the details of how you will do that in the future without writing macro code, variable definitions, etc. that you will have to remember to go back and change later. For example, the last example above will almost certainly change to something like this in the future:

-module(foo).

-export([start/0]).

start() ->

io:fwrite("~p~n", [code()]).

code() ->

{ok, Code} = some_init_module:get_code(),

Code.

Keep this in mind. It makes Erlang almost as prototype-friendly as Guile or Scheme.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值