Thursday, July 20, 2017

LEX PROGRAMS

----------------------------------------------------------------------------------------------------------------------
BASIC LEX PROGRAM TO FIND THE USER LOG IN
-------------------------------------------------------------------------------------------------------------------------
*  with the user's login name (e.g. lgao)
 * Usage: (1) $ flex sample1.lex
 *        (2) $ gcc lex.yy.c -lfl
 *        (3) $ ./a.out
 *            stdin> username
 *          stdin> Ctrl-D
 * Question: What is the purpose of '%{' and '%}'?
 *           What else could be included in this section?
 */

%{
/* need this for the call to getlogin() below */
#include
%}

%%
username    printf("%s\n", getlogin());
%%

main()
{
  yylex();
}

-------------------------------------------------------------------------------------------------------------------------
PROGRAM NO :2 LEX PROGRAM TO DISPLAY VERB OR NOT/ NUMBER TYPE
---------------------------------------------------------------------------------------------------------------------------
%{
/*PROG NO :2 LEX PROGRAM TO DISPLAY VERB OR NOT/*/
%}

%%
raj |
kiran |
sony |
pranathi |
ravi   printf("\n%s is a NOUN",yytext);
singing |
dancing |
sleeping |
crawling |
jumping   {printf("\n%s is a VERB",yytext); printf("\n\t**Just a 2nd Line**");}
[a-zA-Z]+ printf("\n%s is not a verb\n",yytext);
[0][0-9]* printf("\n%s is an OCTAL Number", yytext);
[x|X][0-9A-F]* printf("\n%s is an HEXA DECIMAL Number", yytext);
[0-9]+[0-9]* printf("\n%s is a NUMBER", yytext);
.    printf("\n\t\t\tUnexpected or a Spl Char\n");
%%

int main()
{
    yylex();
    return 0;
}
int yywrap()
{
  return 0;
}

/*
OUTPUT:
D:\CDProgs>flex lex1.l
D:\CDProgs>gcc lex.yy.c
D:\CDProgs>a
raj  sleeping ravi singing 04563  x98AF  fine
raj is a NOUN
                        Unexpected or a Spl Char

                        Unexpected or a Spl Char
sleeping is a VERB
        **Just a 2nd Line**
                        Unexpected or a Spl Char
ravi is a NOUN
                        Unexpected or a Spl Char
singing is a VERB
        **Just a 2nd Line**
                        Unexpected or a Spl Char
04563 is an OCTAL Number
                        Unexpected or a Spl Char
                        Unexpected or a Spl Char
x98AF is an HEXA DECIMAL Number
                        Unexpected or a Spl Char
                        Unexpected or a Spl Char
fine is not a verb
*/
-------------------------------------------------------------------------------------------------------------------------
PROGRAM-3- GIVEN INPUT IS WORD OR TEXT
--------------------------------------------------------------------------------------------------------------------------
%{
#include
%}

%%

[a-zA-z]+    printf("[%s] is a word",yytext);
.            printf("[%s] is a char",yytext);
%%


int main(void)
{
   yylex();
   return 0;
}
int yywrap()
{
  return 0;
}

No comments:

Post a Comment