io:fwrite(Code). ...">

Erlang variable

I have a very simple Erlang program:

-module(test).
-export([start/0]).

Code = "Z00887". 
start() -> io:fwrite(Code).

      

And I am following 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 to use variables correctly in my code.

+3


source to share


1 answer


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

Also, don't 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 throws an error: Code = "Wee~!", io:format(Code).

and will not be caught by the compiler.

The most common task is to define a variable inside a function:

-module(foo).
-export([start/0]).

start() ->
    Code = "Z00887",
    io:fwrite("~p~n", [Code]).

      

You can also just use the value directly:

-module(foo).
-export([start/0]).

start() ->
    io:fwrite("Z00887~n").

      

Or you can define a macro for the whole module:



-module(foo).
-export([start/0]).

-define(CODE, "Z00887").

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

      

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

-module(foo).
-export([start/0]).

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

code() -> "Z00887".

      

This latest version is actually not as strange as it might seem at first glance. Very often when developing your code early on, you will know that you need some value that you will need to obtain in some way, but do not want to worry about the details of it yet. The stub function is a great way to hide the details of how you will do it in the future, without writing down macros, variable definitions, etc. that you will have to remember to come 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.

      

Remember this. This makes Erlang almost as primitive as Guile or Scheme.

+6


source







All Articles