• Input to Lex is divided into three sections with %% dividing the sections.
This is best illustrated by example. The first example is the shortest possible
lex file:
%%
%%
[aeiouAEIOU] { v++;}
[a-zA-Z] { c++; }
%%
main()
{
printf("ENTER INTPUT : \n");
yylex();
printf("VOWELS=%d\nCONSONANTS=%d\n",v,c);
}
How to run lex file
go to the program directory and run the following commands
1. lex filename.l (Compiling lex file)
2. cc lex.yy.c –ll (Compiling c file)
3. ./a.out (Running c code)
this will show the out put of your program.
lex Output
• The goal of lex is to generate the code for a C function named yylex(). This
function is called with no operands. It returns an int value. A value of 0 is
returned when end-of-file is reached; otherwise, yylex() returns a value
indicating what kind of token was found.
• lex also creates two important external data objects: A string named yytext.
This string contains a sequence of characters making up a single input
token. The token is read from the stream yyin, which, by default, is the
standard input (stdin). An integer variable named yyleng. This gives the
number of characters in the yytext string.
• In most lex programs, a token in yytext has an associated value that must
be calculated and passed on to the supporting program. By convention,
yacc names this data object yylval. For example, if yylex() reads a token
which is an integer, yytext contains the string of digits that made up the
integer, while yylval typically contains the actual value of the integer. By
default, yylval is declared to be an int, but there are ways to change this
default.