Variables are used to store values of simple and composite data types. In Erlang, they always start with an uppercase letter, followed by upper- and lowercase letters, integers, and underscores. They may not contain other “special” characters. Examples of variables include the following:
A_long_variable_name Flag Name2 DbgFlag
Erlang variables differ from variables in most conventional programming languages. In the scope of a function, including the Erlang shell process, once you’ve bound a variable, you cannot change its value. This is called single assignment. So, if you need to do a computation and manipulate the value of a variable, you need to store the results in a new variable. For example, writing the following:
Double = 2, Double = Double * Double
would result in a runtime error, because
Double is already bound to the integer
2. Trying to bind it to the integer
4 fails as it is already bound. As mentioned,
the way around this feature is to bind the results in a fresh
Double = 2, NewDouble = Double * Double
Single assignment of variables might feel awkward at first, but you’ll get used to it very quickly. It encourages you to write shorter functions and puts in place a discipline that often results in code with fewer errors. It also makes debugging of errors related to incorrect values easy, as tracing the source of the error to the place where the value was bound can lead to only one place.
All calls with variables in Erlang are call by value: all arguments ...