Although the "Compilation Principles" published in Tsinghua University is related to the introduction of TEX and the method of use, after all, as a appendix, it is natural to discuss it. However, there is also an internet, everything is much simpler. Google has a lot of articles, while watching, while writing, I think Lex is still very easy.
example 1:
% {
INT NUM_LINES = 0, NUM_CHARS = 0, Num_Words = 0;
%}
%%
/ n { Num_Lines; Num_Chars;}
. { Num_Chars;}
[A-ZA-Z] * { Num_Words;}
%%
Main ()
{
Num_Lines = 0;
Num_Chars = 0;
Yylex ();
Printf ("Lines:% D / NCHARS:% D / NWORDS:% D / N", Num_Lines, Num_Chars, Num_Words;
}
In general, one LEX file consists of three parts, and each portion is separated by %%. Example 1 clearly showed this structure.
first part:
% {
INT NUM_LINES = 0, NUM_CHARS = 0, Num_Words = 0;
%}
The role is to declare three global variables to transfer values between Lex and C-source programs,% {and%} must not forget, otherwise the Lex compiler will not write the statements between them into C. Source code.
the second part:
/ n { Num_Lines; Num_Chars;}
. { Num_Chars;}
[A-ZA-Z] * { Num_Words;}
It is the conversion rule, and the function does not need to explain, and it will be understood.
the third part:
Main ()
{
Yylex ();
Printf ("LINES:% D / TCHARS:% D / TORDS:% D / N", Num_Lines, Num_Chars, Num_Words);
}
Since Lex is used here, the C is used as a host language, so it can be placed here.
Compile and run:
Lex f1.l
GCC lex.l.c -of1 -ll
./f1 The result came out. No strength, a record of the number of registers, the number of characters, and the number of words is constructed.