Underscore Variables
There’s one more thing to say about variables. The special syntax _VarName is used for a normal variable, not an anonymous variable. Normally the compiler will generate a warning if a variable is used only once in a clause since this is usually the sign of an error. If the variable is used only once but starts with an underscore, the warning message will not be generated.
There are two main uses of underscore variables:
- To name a variable that we don’t intend to use. That is, writing open(File, _Mode) makes the program more readable than writing open(File, _).
- For debugging purposes. For example, suppose we write this:
some_func(X) ->
{P, Q} = some_other_func(X),
io:format("Q = ~p~n", [Q]),
P.
This compiles without an error message. Now comment out the format statement:
some_func(X) ->
{P, Q} = some_other_func(X),
%% io:format("Q = ~p~n", [Q]),
P.
If we compile this, the compiler will issue a warning that the variable Q is not used.
If we rewrite the function like this:
some_func(X) ->
{P, _Q} = some_other_func(X),
io:format("_Q = ~p~n", [_Q]),
P.
then we can comment out the format statement, and the compiler will not complain.