English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Erlang Pattern Matching

Patterns look the same as terms—they can be simple text, such as atoms and numbers, or compound words like tuples and lists, or a mixture of both. They can also contain variables, which are alphanumeric strings starting with uppercase letters or underscores. A special "anonymous variable" _ (underscore) is used when you do not care about the value to match and will not use it.

If the pattern matches the term with the same "shape", then the pattern matches, and the encountered atom is the same. For example, the following match is successful-

  • B = 1.

  • 2 = 2.

  • {ok, C} = {ok,40}.

  • [H | T] = [1,2,3,4].

Please note that in the fourth example, the vertical bar (|) represents the beginning and end of the list, as described in the clause. Also note that the left-hand side should match the right-hand side, which is the normal case for patterns.

The following pattern matching examples will fail.

  • 1 = 2.

  • {ok, A} = {error, "Unknown issue"}.

  • [H | T] = [].

For pattern matching operators, failure will cause an error and exit the process. The error will introduce how to catch and handle this error. Patterns are used to select which clause of the function will be executed.