DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
lex

Writing lex programs

A lex specification consists of a mandatory rules section, and optional sections for definitions and user subroutines.

The definitions section, if present, must be the first section in the lex program. The mandatory rules section follows the definitions; if there are no definitions, then the rules section is first. In both cases, the rules section must start with the delimiter %%. If there is a subroutines section, it follows the rules section and is separated from the rules by another %% delimiter. If there is no second %% delimiter, the rules section is presumed to continue to the end of the program.

The following is a small, though complete, lex specification, illustrating all three sections:

  1 %{
  2 int count;
  3 %}
  4 %%
  5 fly             { count++; noise(); }
  6 dog             { printf("Woof!\n"); }
  7 man             { printf("Hello world!\n"); }
  8 %%
  9 noise()
 10 {
 11         printf("Bzzzz!\n");
 12 }
In this example, the definitions section (lines 1-3) declares a variable which is used as a counter later in the program. The rules section (lines 4-7) consists of three rules, each of which consists of a pattern, followed by some C code. The subroutines section (lines 8-12) defines a function that is used in one of the actions.
Next topic: Rules section
Previous topic: Creation and use of a lexical analyzer with lex

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003