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:

  1. X
  2. Name1
  3. PhoneNumber
  4. Phone_number
  5. _
  6. _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:

  1. [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:

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

can be rewritten to be more readable:

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

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:

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

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

  1. {_,_} = {1,2}

But this fails:

  1. {_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.