Erl_Interface

Reference Manual

Version 3.13

Table of Contents

erl_format

C Library

erl_format

Library Summary

Create and match Erlang terms.

Description

This module contains two routines: one general function for creating Erlang terms and one for pattern matching Erlang terms.

Exports

ETERM *erl_format(
FormatStr,
...)

Types

char *FormatStr;

A general function for creating Erlang terms using a format specifier and a corresponding set of arguments, much in the way printf() works.

FormatStr is a format specification string. The valid format specifiers are as follows:

  • ~i - Integer
  • ~f - Floating point
  • ~a - Atom
  • ~s - String
  • ~w - Arbitrary Erlang term

For each format specifier included in FormatStr, there must be a corresponding argument following FormatStr. An Erlang term is built according to FormatStr with values and Erlang terms substituted from the corresponding arguments, and according to the individual format specifiers. For example:

erl_format("[{name,~a},{age,~i},{data,~w}]",
           "madonna",
           21,
           erl_format("[{adr,~s,~i}]","E-street",42));

This creates an (ETERM *) structure corresponding to the Erlang term [{name,madonna},{age,21},{data,[{adr,"E-street",42}]}]

The function returns an Erlang term, or NULL if FormatStr does not describe a valid Erlang term.

int erl_match(
Pattern,
Term)

Types

ETERM *Pattern,*Term;

This function is used to perform pattern matching similar to that done in Erlang. For matching rules and more examples, see section Pattern Matching in the Erlang Reference Manual.

  • Pattern is an Erlang term, possibly containing unbound variables.
  • Term is an Erlang term that we wish to match against Pattern.

Term and Pattern are compared and any unbound variables in Pattern are bound to corresponding values in Term.

If Term and Pattern can be matched, the function returns a non-zero value and binds any unbound variables in Pattern. If Term and Pattern do not match, 0 is returned. For example:

ETERM *term, *pattern, *pattern2;
term1    = erl_format("{14,21}");
term2    = erl_format("{19,19}");
pattern1 = erl_format("{A,B}");
pattern2 = erl_format("{F,F}");
if (erl_match(pattern1, term1)) {
  /* match succeeds:
   * A gets bound to 14, 
   * B gets bound to 21 
   */
  ...  
}
if (erl_match(pattern2, term1)) {
  /* match fails because F cannot be 
   * bound to two separate values, 14 and 21
   */
  ...
}
if (erl_match(pattern2, term2)) {
  /* match succeeds and F gets bound to 19 */
  ...
}

erl_var_content() can be used to retrieve the content of any variables bound as a result of a call to erl_match().