All Pages All Books|
|
||
|
%%
/* match everything except newline */ . ECHO;
/* match newline */ \n ECHO;
%%
int yywrap(void) {
return 1; }
int main(void) {
yylex();
return 0; }
Two patterns have been specified in the rules section. Each pattern must begin in column one. This is followed by whitespace (space, tab or newline), and an optional action associated with the pattern. The action may be a single C statement, or multiple C statements enclosed in braces. Anything not starting in column one is copied verbatim to the generated C file. We may take advantage of this behavior to specify comments in our lex file. In this example there are two patterns, “.” and “\n”, with an ECHO action associated for each pattern. Several macros and variables are predefined by lex. ECHO is a macro that writes code matched by the pattern. This is the default action for any unmatched strings. Typically, ECHO is defined as:
#define ECHO fwrite(yytext, yyleng, 1, yyout)
Variable yytext is a pointer to the matched string (NULL-terminated), and yyleng is the length of the matched string. Variable yyout is the output file, and defaults to stdout. Function yywrap is called by lex when input is exhausted. Return 1 if you are done, or 0 if more processing is required. Every C program requires a main function. In this case, we simply call yylex, the main entry-point for lex. Some implementations of lex include copies of main and yywrap in a library, eliminating the need to code them explicitly. This is why our first example, the shortest lex program, functioned properly.
|
||
|
|
||
|
9
|
||
|
|
||
All Pages All Books