Variable in Erlang -


i have simple erlang program:

-module(test). -export([start/0]).  code = "z00887".  start() -> io:fwrite(code). 

and have follows 2 errors:

c:/erl6.1/dev/test.erl:4: syntax error before: code
c:/erl6.1/dev/test.erl:5: variable 'code' unbound

could please me correctly using variables in code.

you defining variable global module, not allowed. remember, "variables" in erlang "symbols", there no concept of "global" constant across functions or processes. closest thing in erlang macro defined in module, if value needed in 1 place , want name must done within function definition.

also, not use io:fwrite/1 or io:format/1. problem possible inclusion of escape characters in string passing. example, causes error: code = "wee~!", io:format(code). , not caught compiler.

the common thing define variable within function:

-module(foo). -export([start/0]).  start() ->     code = "z00887",     io:fwrite("~p~n", [code]). 

you use value directly:

-module(foo). -export([start/0]).  start() ->     io:fwrite("z00887~n"). 

or define macro across whole module:

-module(foo). -export([start/0]).  -define(code, "z00887").  start() ->     io:fwrite("~p~n", [?code]). 

or define stub function returns want:

-module(foo). -export([start/0]).  start() ->     io:fwrite("~p~n", [code()]).  code() -> "z00887". 

this last version not weird may seem @ first. when developing code on know need value somewhere need derive in way, don't want worry details of yet. stub function excellent way hide details of how in future without writing macro code, variable definitions, etc. have remember go , change later. example, last example above change in future:

-module(foo). -export([start/0]).  start() ->     io:fwrite("~p~n", [code()]).  code() ->     {ok, code} = some_init_module:get_code(),     code. 

keep in mind. makes erlang prototype-friendly guile or scheme.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -