## 8.3 Variables

A variable is an expression. If a variable is bound to a value, the return value is this value. Unbound variables are only allowed in patterns.

Variables start with an uppercase letter or underscore (_). Variables can contain alphanumeric characters, underscore and @.

Examples:

XName1PhoneNumberPhone_number__Height

Variables are bound to values using pattern matching. Erlang uses single assignment, that is, a variable can only be bound once.

The anonymous variable is denoted by underscore (_) and can be used when a variable is required but its value can be ignored.

Example:

[H|_] = [1,2,3]

Variables starting with underscore (_), for example, _Height, are normal variables, not anonymous. They are however ignored by the compiler in the sense that they do not generate any warnings for unused variables.

Example:

The following code:

member(_, []) ->    [].

can be rewritten to be more readable:

member(Elem, []) ->    [].

This causes a warning for an unused variable, Elem, if the code is compiled with the flag warn_unused_vars set. Instead, the code can be rewritten to:

member(_Elem, []) ->    [].

Notice that since variables starting with an underscore are not anonymous, this matches:

{_,_} = {1,2}

But this fails:

{_N,_N} = {1,2}

The scope for a variable is its function clause. Variables bound in a branch of an if, case, or receive expression must be bound in all branches to have a value outside the expression. Otherwise they are regarded as 'unsafe' outside the expression.

For the try expression variable scoping is limited so that variables bound in the expression are always 'unsafe' outside the expression.