[GoLUG] [parse] An improved word count Flex program
Steve Litt
slitt at troubleshooters.com
Fri Nov 24 19:43:44 EST 2023
Hi all,
Yesterday I submitted Flex program wc.l that acted kinda sorta like the
Linux wc program. If you remember, I had all sorts of extraneous code
in there only to kill some errors and warnings. Further reading
indicated I could kill all that junk with the following line, which is
put above the declaration section:
%option noyywrap noinput nounput
Also, I discovered the true matching order, which I'll comment on in a
later email, so I slightly rearranged the rules section. The improved
and de-kludged program follows:
=================================================================
/* Almost just like Unix wc
Adapted from program fb1-1.l
in John Levine's "Flex & Bison"
book at https://www.oreilly.com/
library/view/flex-bison/9780596805418/
To compile and run, assuming this file
is called wc.l, perform the following
three commands, where test.txt is a
sample text file containing words
separated by spaces and paragraphs
separated by blank lines:
flex wc.l
gcc -Wall lex.yy.c
cat test.txt | ./a.out
*/
/* Following non-comment line does following:
Kill yywrap not found err,
kill input redefined warning
kill yyunput redefined warning */
%option noyywrap noinput nounput
%{
/* Global definitions/declarations occur
here in the declarations section.
*/
int chars = 0;
int words = 0;
int lines = 0;
%}
%%
\n { chars++; lines++;}
[a-zA-Z]+ { words++; chars += strlen(yytext); }
. { chars++; }
%%
int main(int argc, char **argv){
yylex();
printf("%8d%8d%8d\n", lines, words, chars);
}
=================================================================
SteveT
Steve Litt
Autumn 2023 featured book: Rapid Learning for the 21st Century
http://www.troubleshooters.com/rl21
More information about the GoLUG
mailing list