JavaScript is required to for searching.
Skip Navigation Links
Exit Print View
man pages section 1: User Commands     Oracle Solaris 10 8/11 Information Library
search filter icon
search icon

Document Information

Preface

Introduction

User Commands

acctcom(1)

adb(1)

addbib(1)

admin(1)

aedplot(1B)

alias(1)

allocate(1)

amt(1)

appcert(1)

apptrace(1)

apropos(1)

ar(1)

arch(1)

as(1)

asa(1)

at(1)

atoplot(1B)

atq(1)

atrm(1)

audioconvert(1)

audioplay(1)

audiorecord(1)

auths(1)

auto_ef(1)

awk(1)

banner(1)

basename(1)

basename(1B)

batch(1)

bc(1)

bdiff(1)

bfs(1)

bg(1)

bgplot(1B)

biff(1B)

break(1)

cal(1)

calendar(1)

cancel(1)

case(1)

cat(1)

cc(1B)

cd(1)

cdc(1)

cdrw(1)

chdir(1)

checkeq(1)

checknr(1)

chgrp(1)

chkey(1)

chmod(1)

chown(1)

chown(1B)

ckdate(1)

ckgid(1)

ckint(1)

ckitem(1)

ckkeywd(1)

ckpath(1)

ckrange(1)

ckstr(1)

cksum(1)

cktime(1)

ckuid(1)

ckyorn(1)

clear(1)

cmp(1)

cocheck(1F)

cocreate(1F)

codestroy(1F)

col(1)

comb(1)

comm(1)

command(1)

compress(1)

continue(1)

coproc(1F)

coreceive(1F)

cosend(1F)

cp(1)

cpio(1)

cpp(1)

cputrack(1)

crle(1)

crontab(1)

crtplot(1B)

crypt(1)

csh(1)

csplit(1)

ct(1C)

ctags(1)

ctrun(1)

ctstat(1)

ctwatch(1)

cu(1C)

cut(1)

date(1)

dc(1)

deallocate(1)

decrypt(1)

delta(1)

deroff(1)

df(1B)

dhcpinfo(1)

diff(1)

diff3(1)

diffmk(1)

digest(1)

digestp(1)

dircmp(1)

dirname(1)

dirs(1)

dis(1)

disable(1)

dispgid(1)

dispuid(1)

dos2unix(1)

download(1)

dpost(1)

dtappsession(1)

du(1)

du(1B)

dumbplot(1B)

dump(1)

dumpcs(1)

dumpkeys(1)

echo(1)

echo(1B)

echo(1F)

ed(1)

edit(1)

egrep(1)

eject(1)

elfdump(1)

elfedit(1)

elfsign(1)

elfwrap(1)

enable(1)

encrypt(1)

enhance(1)

env(1)

eqn(1)

errange(1)

errdate(1)

errgid(1)

errint(1)

erritem(1)

error(1)

errpath(1)

errstr(1)

errtime(1)

erruid(1)

erryorn(1)

eval(1)

ex(1)

exec(1)

exit(1)

expand(1)

export(1)

exportfs(1B)

expr(1)

expr(1B)

exstr(1)

face(1)

factor(1)

false(1)

fastboot(1B)

fasthalt(1B)

fc(1)

fdformat(1)

fg(1)

fgrep(1)

file(1)

file(1B)

filep(1)

filesync(1)

filofaxp(1)

find(1)

finger(1)

fmlcut(1F)

fmlexpr(1F)

fmlgrep(1F)

fmli(1)

fmt(1)

fmtmsg(1)

fold(1)

for(1)

foreach(1)

franklinp(1)

from(1B)

ftp(1)

ftpcount(1)

ftpwho(1)

function(1)

gcore(1)

gencat(1)

geniconvtbl(1)

genlayouttbl(1)

genmsg(1)

get(1)

getconf(1)

getfacl(1)

getfrm(1F)

getitems(1F)

getlabel(1)

getopt(1)

getoptcvt(1)

getopts(1)

gettext(1)

gettxt(1)

getzonepath(1)

gigiplot(1B)

glob(1)

goto(1)

gprof(1)

graph(1)

grep(1)

groups(1)

groups(1B)

grpck(1B)

hash(1)

hashcheck(1)

hashmake(1)

hashstat(1)

head(1)

help(1)

helpdate(1)

helpgid(1)

helpint(1)

helpitem(1)

helppath(1)

helprange(1)

helpstr(1)

helptime(1)

helpuid(1)

helpyorn(1)

history(1)

hostid(1)

hostname(1)

hp7221plot(1B)

hpplot(1B)

i286(1)

i386(1)

i486(1)

i860(1)

iAPX286(1)

iconv(1)

idnconv(1)

if(1)

implot(1B)

indicator(1F)

indxbib(1)

install(1B)

ipcrm(1)

ipcs(1)

isainfo(1)

isalist(1)

jobs(1)

join(1)

jsh(1)

kbd(1)

kdestroy(1)

keylogin(1)

keylogout(1)

kill(1)

kinit(1)

klist(1)

kmdb(1)

kmfcfg(1)

kpasswd(1)

krb5-config(1)

ksh(1)

ktutil(1)

lari(1)

last(1)

lastcomm(1)

ld(1)

ld(1B)

ldap(1)

ldapadd(1)

ldapdelete(1)

ldaplist(1)

ldapmodify(1)

ldapmodrdn(1)

ldapsearch(1)

ldd(1)

ld.so.1(1)

let(1)

lex(1)

limit(1)

line(1)

lint(1B)

list_devices(1)

listusers(1)

llc2_autoconfig(1)

llc2_config(1)

llc2_stats(1)

ln(1)

ln(1B)

loadkeys(1)

locale(1)

localedef(1)

logger(1)

logger(1B)

login(1)

logname(1)

logout(1)

longline(1F)

look(1)

lookbib(1)

lorder(1)

lp(1)

lpc(1B)

lpq(1B)

lpr(1B)

lprm(1B)

lpstat(1)

lptest(1B)

ls(1)

ls(1B)

m4(1)

mac(1)

mach(1)

machid(1)

madv.so.1(1)

mail(1)

Mail(1B)

mail(1B)

mailcompat(1)

mailp(1)

mailq(1)

mailstats(1)

mailx(1)

make(1S)

man(1)

mconnect(1)

mcs(1)

mdb(1)

mesg(1)

message(1F)

mixerctl(1)

mkdir(1)

mkmsgs(1)

mkstr(1B)

mktemp(1)

moe(1)

more(1)

mp(1)

mpss.so.1(1)

msgfmt(1)

mt(1)

mv(1)

nawk(1)

nca(1)

ncab2clf(1)

ncakmod(1)

neqn(1)

newform(1)

newgrp(1)

news(1)

newsp(1)

newtask(1)

nice(1)

NIS+(1)

nis+(1)

nis(1)

niscat(1)

nischgrp(1)

nischmod(1)

nischown(1)

nischttl(1)

nisdefaults(1)

niserror(1)

nisgrep(1)

nisgrpadm(1)

nisln(1)

nisls(1)

nismatch(1)

nismkdir(1)

nisopaccess(1)

nispasswd(1)

nisrm(1)

nisrmdir(1)

nistbladm(1)

nistest(1)

nl(1)

nm(1)

nohup(1)

notify(1)

nroff(1)

od(1)

on(1)

onintr(1)

optisa(1)

pack(1)

page(1)

pagesize(1)

pargs(1)

passwd(1)

paste(1)

patch(1)

pathchk(1)

pathconv(1F)

pax(1)

pcat(1)

pcred(1)

pdp11(1)

perl(1)

pfcsh(1)

pfexec(1)

pfiles(1)

pfksh(1)

pflags(1)

pfsh(1)

pg(1)

pgrep(1)

pkginfo(1)

pkgmk(1)

pkgparam(1)

pkgproto(1)

pkgtrans(1)

pkill(1)

pktool(1)

plabel(1)

pldd(1)

plimit(1)

plot(1B)

plottoa(1B)

pmap(1)

popd(1)

postdaisy(1)

postdmd(1)

postio(1)

postmd(1)

postplot(1)

postprint(1)

postreverse(1)

posttek(1)

ppgsz(1)

ppriv(1)

pr(1)

praliases(1)

prctl(1)

preap(1)

prex(1)

print(1)

printenv(1B)

printf(1)

priocntl(1)

proc(1)

prof(1)

profiles(1)

projects(1)

prs(1)

prt(1)

prun(1)

ps(1)

ps(1B)

psig(1)

pstack(1)

pstop(1)

ptime(1)

ptree(1)

pushd(1)

pvs(1)

pwait(1)

pwd(1)

pwdx(1)

ranlib(1)

rcapstat(1)

rcp(1)

rdist(1)

read(1)

readfile(1F)

readonly(1)

red(1)

refer(1)

regcmp(1)

regex(1F)

rehash(1)

reinit(1F)

remote_shell(1)

remsh(1)

renice(1)

repeat(1)

reset(1B)

reset(1F)

return(1)

rksh(1)

rlogin(1)

rm(1)

rmail(1)

rmdel(1)

rmdir(1)

rmformat(1)

roffbib(1)

roles(1)

rpcgen(1)

rpm2cpio(1)

rsh(1)

run(1F)

runat(1)

rup(1)

rup(1C)

ruptime(1)

rusage(1B)

rusers(1)

rwho(1)

sact(1)

sag(1)

sar(1)

sccs(1)

sccs-admin(1)

sccs-cdc(1)

sccs-comb(1)

sccs-delta(1)

sccsdiff(1)

sccs-get(1)

sccs-help(1)

sccs-prs(1)

sccs-prt(1)

sccs-rmdel(1)

sccs-sact(1)

sccs-sccsdiff(1)

sccs-unget(1)

sccs-val(1)

scp(1)

script(1)

sdiff(1)

sed(1)

sed(1B)

select(1)

set(1)

set(1F)

setcolor(1F)

setenv(1)

setfacl(1)

setlabel(1)

setpgrp(1)

settime(1)

sftp(1)

sh(1)

shell(1F)

shell_builtins(1)

shift(1)

shutdown(1B)

size(1)

sleep(1)

snca(1)

snmpstatus(1)

soelim(1)

sort(1)

sortbib(1)

sotruss(1)

source(1)

sparc(1)

spell(1)

spellin(1)

spline(1)

split(1)

srchtxt(1)

ssh(1)

ssh-add(1)

ssh-agent(1)

ssh-http-proxy-connect(1)

ssh-keygen(1)

ssh-keyscan(1)

ssh-socks5-proxy-connect(1)

stop(1)

strchg(1)

strconf(1)

strings(1)

strip(1)

stty(1)

stty(1B)

sum(1)

sum(1B)

sun(1)

suspend(1)

svcprop(1)

svcs(1)

switch(1)

symorder(1)

sysV-make(1)

t300(1)

t300(1B)

t300s(1)

t300s(1B)

t4013(1B)

t4014(1)

t450(1)

t450(1B)

tabs(1)

tail(1)

talk(1)

tar(1)

tbl(1)

tcopy(1)

tee(1)

tek(1)

tek(1B)

telnet(1)

test(1)

test(1B)

test(1F)

tftp(1)

time(1)

timemanp(1)

times(1)

timesysp(1)

timex(1)

tip(1)

tnfdump(1)

tnfxtract(1)

touch(1)

touch(1B)

tplot(1)

tput(1)

tr(1)

tr(1B)

trap(1)

troff(1)

true(1)

truss(1)

tset(1B)

tsort(1)

tty(1)

type(1)

typeset(1)

u370(1)

u3b(1)

u3b15(1)

u3b2(1)

u3b5(1)

ucblinks(1B)

ul(1)

ulimit(1)

umask(1)

unalias(1)

uname(1)

uncompress(1)

unexpand(1)

unget(1)

unhash(1)

unifdef(1)

uniq(1)

units(1)

unix2dos(1)

unlimit(1)

unpack(1)

unset(1)

unset(1F)

unsetenv(1)

until(1)

uptime(1)

users(1B)

uucp(1C)

uudecode(1C)

uuencode(1C)

uuglist(1C)

uulog(1C)

uuname(1C)

uupick(1C)

uustat(1C)

uuto(1C)

uux(1C)

vacation(1)

val(1)

valdate(1)

valgid(1)

valint(1)

valpath(1)

valrange(1)

valstr(1)

valtime(1)

valuid(1)

valyorn(1)

vax(1)

vc(1)

vedit(1)

ver(1)

vgrind(1)

vi(1)

view(1)

vipw(1B)

volcancel(1)

volcheck(1)

volmissing(1)

volrmmount(1)

vplot(1B)

vsig(1F)

w(1)

wait(1)

wc(1)

what(1)

whatis(1)

whence(1)

whereis(1B)

which(1)

while(1)

who(1)

whoami(1B)

whocalls(1)

whois(1)

write(1)

xargs(1)

xgettext(1)

xstr(1)

yacc(1)

yes(1)

ypcat(1)

ypmatch(1)

yppasswd(1)

ypwhich(1)

zcat(1)

zlogin(1)

zonename(1)

lex

- generate programs for lexical tasks

Synopsis

lex [-cntv] [-e | -w] [-V -Q [y | n]] [file]...

Description

The lex utility generates C programs to be used in lexical processing of character input, and that can be used as an interface to yacc. The C programs are generated from lex source code and conform to the ISO C standard. Usually, the lex utility writes the program it generates to the file lex.yy.c. The state of this file is unspecified if lex exits with a non-zero exit status. See EXTENDED DESCRIPTION for a complete description of the lex input language.

Options

The following options are supported:

-c

Indicates C-language action (default option).

-e

Generates a program that can handle EUC characters (cannot be used with the -w option). yytext[ ] is of type unsigned char[ ].

-n

Suppresses the summary of statistics usually written with the -v option. If no table sizes are specified in the lex source code and the -v option is not specified, then -n is implied.

-t

Writes the resulting program to standard output instead of lex.yy.c.

-v

Writes a summary of lex statistics to the standard error. (See the discussion of lex table sizes under the heading Definitions in lex.) If table sizes are specified in the lex source code, and if the -n option is not specified, the -v option may be enabled.

-w

Generates a program that can handle EUC characters (cannot be used with the -e option). Unlike the -e option, yytext[ ] is of type wchar_t[ ].

-V

Prints out version information on standard error.

-Q[y|n]

Prints out version information to output file lex.yy.c by using -Qy. The -Qn option does not print out version information and is the default.

Operands

The following operand is supported:

file

A pathname of an input file. If more than one such file is specified, all files will be concatenated to produce a single lex program. If no file operands are specified, or if a file operand is -, the standard input will be used.

OUTPUT

The lex output files are described below.

Stdout

If the -t option is specified, the text file of C source code output of lex will be written to standard output.

Stderr

If the -t option is specified informational, error and warning messages concerning the contents of lex source code input will be written to the standard error.

If the -t option is not specified:

  1. Informational error and warning messages concerning the contents of lex source code input will be written to either the standard output or standard error.

  2. If the -v option is specified and the -n option is not specified, lex statistics will also be written to standard error. These statistics may also be generated if table sizes are specified with a % operator in the Definitions in lex section (see EXTENDED DESCRIPTION), as long as the -n option is not specified.

Output Files

A text file containing C source code will be written to lex.yy.c, or to the standard output if the -t option is present.

Extended Description

Each input file contains lex source code, which is a table of regular expressions with corresponding actions in the form of C program fragments.

When lex.yy.c is compiled and linked with the lex library (using the -l l operand with c89 or cc), the resulting program reads character input from the standard input and partitions it into strings that match the given expressions.

When an expression is matched, these actions will occur:

During pattern matching, lex searches the set of patterns for the single longest possible match. Among rules that match the same number of characters, the rule given first will be chosen.

The general format of lex source is:

Definitions
%%
Rules
%%
User Subroutines

The first %% is required to mark the beginning of the rules (regular expressions and actions); the second %% is required only if user subroutines follow.

Any line in the Definitions in lex section beginning with a blank character will be assumed to be a C program fragment and will be copied to the external definition area of the lex.yy.c file. Similarly, anything in the Definitions in lex section included between delimiter lines containing only %{ and %} will also be copied unchanged to the external definition area of the lex.yy.c file.

Any such input (beginning with a blank character or within %{ and %} delimiter lines) appearing at the beginning of the Rules section before any rules are specified will be written to lex.yy.c after the declarations of variables for the yylex function and before the first line of code in yylex. Thus, user variables local to yylex can be declared here, as well as application code to execute upon entry to yylex.

The action taken by lex when encountering any input beginning with a blank character or within %{ and %} delimiter lines appearing in the Rules section but coming after one or more rules is undefined. The presence of such input may result in an erroneous definition of the yylex function.

Definitions in lex

Definitions in lex appear before the first %% delimiter. Any line in this section not contained between %{ and %} lines and not beginning with a blank character is assumed to define a lex substitution string. The format of these lines is:

name substitute

If a name does not meet the requirements for identifiers in the ISO C standard, the result is undefined. The string substitute will replace the string { name } when it is used in a rule. The name string is recognized in this context only when the braces are provided and when it does not appear within a bracket expression or within double-quotes.

In the Definitions in lex section, any line beginning with a % (percent sign) character and followed by an alphanumeric word beginning with either s or S defines a set of start conditions. Any line beginning with a % followed by a word beginning with either x or X defines a set of exclusive start conditions. When the generated scanner is in a %s state, patterns with no state specified will be also active; in a %x state, such patterns will not be active. The rest of the line, after the first word, is considered to be one or more blank-character-separated names of start conditions. Start condition names are constructed in the same way as definition names. Start conditions can be used to restrict the matching of regular expressions to one or more states as described in Regular expressions in lex.

Implementations accept either of the following two mutually exclusive declarations in the Definitions in lex section:

%array

Declare the type of yytext to be a null-terminated character array.

%pointer

Declare the type of yytext to be a pointer to a null-terminated character string.

Note: When using the %pointer option, you may not also use the yyless function to alter yytext.

%array is the default. If %array is specified (or neither %array nor %pointer is specified), then the correct way to make an external reference to yyext is with a declaration of the form:

extern char yytext[ ]

If %pointer is specified, then the correct external reference is of the form:

extern char *yytext;

lex will accept declarations in the Definitions in lex section for setting certain internal table sizes. The declarations are shown in the following table.

Table Size Declaration in lex

Declaration
Description
Default
%pn
Number of positions
2500
%nn
Number of states
500
%a n
Number of transitions
2000
%en
Number of parse tree nodes
1000
%kn
Number of packed character classes
10000
%on
Size of the output array
3000

Programs generated by lex need either the -e or -w option to handle input that contains EUC characters from supplementary codesets. If neither of these options is specified, yytext is of the type char[ ], and the generated program can handle only ASCII characters.

When the -e option is used, yytext is of the type unsigned char[ ] and yyleng gives the total number of bytes in the matched string. With this option, the macros input(), unput(c), and output(c) should do a byte-based I/O in the same way as with the regular ASCII lex. Two more variables are available with the -e option, yywtext and yywleng, which behave the same as yytext and yyleng would under the -w option.

When the -w option is used, yytext is of the type wchar_t[ ] and yyleng gives the total number of characters in the matched string. If you supply your own input(), unput(c), or output(c) macros with this option, they must return or accept EUC characters in the form of wide character (wchar_t). This allows a different interface between your program and the lex internals, to expedite some programs.

Rules in lex

The Rules in lex source files are a table in which the left column contains regular expressions and the right column contains actions (C program fragments) to be executed when the expressions are recognized.

ERE action
ERE action
...

The extended regular expression (ERE) portion of a row will be separated from action by one or more blank characters. A regular expression containing blank characters is recognized under one of the following conditions:

User Subroutines in lex

Anything in the user subroutines section will be copied to lex.yy.c following yylex.

Regular Expressions in lex

The lex utility supports the set of Extended Regular Expressions (EREs) described on regex(5) with the following additions and exceptions to the syntax:

. . .

Any string enclosed in double-quotes will represent the characters within the double-quotes as themselves, except that backslash escapes (which appear in the following table) are recognized. Any backslash-escape sequence is terminated by the closing quote. For example, " \ 01""1" represents a single string: the octal value 1 followed by the character 1.

<state>r

<state1, state2, . . . >r

The regular expression r will be matched only when the program is in one of the start conditions indicated by state, state1, and so forth. For more information, see Actions in lex. As an exception to the typographical conventions of the rest of this document, in this case <state> does not represent a metavariable, but the literal angle-bracket characters surrounding a symbol. The start condition is recognized as such only at the beginning of a regular expression.

r/x

The regular expression r will be matched only if it is followed by an occurrence of regular expression x. The token returned in yytext will only match r. If the trailing portion of r matches the beginning of x, the result is unspecified. The r expression cannot include further trailing context or the $ (match-end-of-line) operator; x cannot include the ^ (match-beginning-of-line) operator, nor trailing context, nor the $ operator. That is, only one occurrence of trailing context is allowed in a lex regular expression, and the ^ operator only can be used at the beginning of such an expression. A further restriction is that the trailing-context operator / (slash) cannot be grouped within parentheses.

{name}

When name is one of the substitution symbols from the Definitions section, the string, including the enclosing braces, will be replaced by the substitute value. The substitute value will be treated in the extended regular expression as if it were enclosed in parentheses. No substitution will occur if {name} occurs within a bracket expression or within double-quotes.

Within an ERE, a backslash character ( \\, \ a, \ b, \ f, \ n, \ r, \ t, \ v) is considered to begin an escape sequence. In addition, the escape sequences in the following table will be recognized.

A literal newline character cannot occur within an ERE; the escape sequence \ n can be used to represent a newline character. A newline character cannot be matched by a period operator.

Escape Sequences in lex

Escape Sequences in lex
Escape Sequence
Description
Meaning
\digits
A backslash character followed by the longest sequence of one, two or three octal-digit characters (01234567). Ifall of the digits are 0, (that is, representation of the NUL character), the behavior is undefined.
The character whose encoding is represented by the one-, two- or three-digit octal integer. Multi-byte characters require multiple, concatenated escape sequences of this type, including the leading \ for each byte.
\xdigits
A backslash character followed by the longest sequence of hexadecimal-digit characters (01234567abcdefABCDEF). If all of the digits are 0, (that is, representation of the NUL character), the behavior is undefined.
The character whose encoding is represented by the hexadecimal integer.
\c
A backslash character followed by any character not described in this table. (\\, \a, \b, \f, \en, \r, \t, \v).
The character c, unchanged.

The order of precedence given to extended regular expressions for lex is as shown in the following table, from high to low.

Note:

The escaped characters entry is not meant to imply that these are operators, but they are included in the table to show their relationships to the true operators. The start condition, trailing context and anchoring notations have been omitted from the table because of the placement restrictions described in this section; they can only appear at the beginning or ending of an ERE.

ERE Precedence in lex
collation-related bracket symbols
[= =] [: :] [. .]
escaped characters
\<special character>
bracket expression
[ ]
quoting
". . ."
grouping
()
definition
{name}
single-character RE duplication
* + ?
concatenation
interval expression
{m,n}
alternation
|

The ERE anchoring operators ( ^ and $ ) do not appear in the table. With lex regular expressions, these operators are restricted in their use: the ^ operator can only be used at the beginning of an entire regular expression, and the $ operator only at the end. The operators apply to the entire regular expression. Thus, for example, the pattern (^abc)|(def$) is undefined; it can instead be written as two separate rules, one with the regular expression ^abc and one with def$, which share a common action via the special | action (see below). If the pattern were written ^abc|def$, it would match either of abc or def on a line by itself.

Unlike the general ERE rules, embedded anchoring is not allowed by most historical lex implementations. An example of embedded anchoring would be for patterns such as (^)foo($) to match foo when it exists as a complete word. This functionality can be obtained using existing lex features:

^foo/[ \ n]|
" foo"/[ \ n]    /* found foo as a separate word */

Notice also that $ is a form of trailing context (it is equivalent to /\ n and as such cannot be used with regular expressions containing another instance of the operator (see the preceding discussion of trailing context).

The additional regular expressions trailing-context operator / (slash) can be used as an ordinary character if presented within double-quotes, " / "; preceded by a backslash, \ /; or within a bracket expression, [ / ]. The start-condition < and > operators are special only in a start condition at the beginning of a regular expression; elsewhere in the regular expression they are treated as ordinary characters.

The following examples clarify the differences between lex regular expressions and regular expressions appearing elsewhere in this document. For regular expressions of the form r/x, the string matching r is always returned; confusion may arise when the beginning of x matches the trailing portion of r. For example, given the regular expression a*b/cc and the input aaabcc, yytext would contain the string aaab on this match. But given the regular expression x*/xy and the input xxxy, the token xxx, not xx, is returned by some implementations because xxx matches x*.

In the rule ab*/bc, the b* at the end of r will extend r's match into the beginning of the trailing context, so the result is unspecified. If this rule were ab/bc, however, the rule matches the text ab when it is followed by the text bc. In this latter case, the matching of r cannot extend into the beginning of x, so the result is specified.

Actions in lex

The action to be taken when an ERE is matched can be a C program fragment or the special actions described below; the program fragment can contain one or more C statements, and can also include special actions. The empty C statement ; is a valid action; any string in the lex.yy.c input that matches the pattern portion of such a rule is effectively ignored or skipped. However, the absence of an action is not valid, and the action lex takes in such a condition is undefined.

The specification for an action, including C statements and special actions, can extend across several lines if enclosed in braces:

ERE <one or more blanks> { program statement
program statement }

The default action when a string in the input to a lex.yy.c program is not matched by any expression is to copy the string to the output. Because the default behavior of a program generated by lex is to read the input and copy it to the output, a minimal lex source program that has just %% generates a C program that simply copies the input to the output unchanged.

Four special actions are available:

|       ECHO;      REJECT;      BEGIN
|

The action | means that the action for the next rule is the action for this rule. Unlike the other three actions, | cannot be enclosed in braces or be semicolon-terminated. It must be specified alone, with no other actions.

ECHO;

Writes the contents of the string yytext on the output.

REJECT;

Usually only a single expression is matched by a given string in the input. REJECT means "continue to the next expression that matches the current input," and causes whatever rule was the second choice after the current rule to be executed for the same input. Thus, multiple rules can be matched and executed for one input string or overlapping input strings. For example, given the regular expressions xyz and xy and the input xyz, usually only the regular expression xyz would match. The next attempted match would start after z. If the last action in the xyz rule is REJECT , both this rule and the xy rule would be executed. The REJECT action may be implemented in such a fashion that flow of control does not continue after it, as if it were equivalent to a goto to another part of yylex. The use of REJECT may result in somewhat larger and slower scanners.

BEGIN

The action:

BEGIN newstate;

switches the state (start condition) to newstate. If the string newstate has not been declared previously as a start condition in the Definitions in lex section, the results are unspecified. The initial state is indicated by the digit 0 or the token INITIAL.

The functions or macros described below are accessible to user code included in the lex input. It is unspecified whether they appear in the C code output of lex, or are accessible only through the -l l operand to c89 or cc (the lex library).

int yylex(void)

Performs lexical analysis on the input; this is the primary function generated by the lex utility. The function returns zero when the end of input is reached; otherwise it returns non-zero values (tokens) determined by the actions that are selected.

int yymore(void)

When called, indicates that when the next input string is recognized, it is to be appended to the current value of yytext rather than replacing it; the value in yyleng is adjusted accordingly.

intyyless(int n)

Retains n initial characters in yytext, NUL-terminated, and treats the remaining characters as if they had not been read; the value in yyleng is adjusted accordingly.

int input(void)

Returns the next character from the input, or zero on end-of-file. It obtains input from the stream pointer yyin, although possibly via an intermediate buffer. Thus, once scanning has begun, the effect of altering the value of yyin is undefined. The character read is removed from the input stream of the scanner without any processing by the scanner.

int unput(int c)

Returns the character c to the input; yytext and yyleng are undefined until the next expression is matched. The result of using unput for more characters than have been input is unspecified.

The following functions appear only in the lex library accessible through the -l l operand; they can therefore be redefined by a portable application:

int yywrap(void)

Called by yylex at end-of-file; the default yywrap always will return 1. If the application requires yylex to continue processing with another source of input, then the application can include a function yywrap, which associates another file with the external variable FILE *yyin and will return a value of zero.

int main(int argc, char *argv[ ])

Calls yylex to perform lexical analysis, then exits. The user code can contain main to perform application-specific operations, calling yylex as applicable.

The reason for breaking these functions into two lists is that only those functions in libl.a can be reliably redefined by a portable application.

Except for input, unput and main, all external and static names generated by lex begin with the prefix yy or YY.

Usage

Portable applications are warned that in the Rules in lex section, an ERE without an action is not acceptable, but need not be detected as erroneous by lex. This may result in compilation or run-time errors.

The purpose of input is to take characters off the input stream and discard them as far as the lexical analysis is concerned. A common use is to discard the body of a comment once the beginning of a comment is recognized.

The lex utility is not fully internationalized in its treatment of regular expressions in the lex source code or generated lexical analyzer. It would seem desirable to have the lexical analyzer interpret the regular expressions given in the lex source according to the environment specified when the lexical analyzer is executed, but this is not possible with the current lex technology. Furthermore, the very nature of the lexical analyzers produced by lex must be closely tied to the lexical requirements of the input language being described, which will frequently be locale-specific anyway. (For example, writing an analyzer that is used for French text will not automatically be useful for processing other languages.)

Examples

Example 1 Using lex

The following is an example of a lex program that implements a rudimentary scanner for a Pascal-like syntax:

%{
/* need this for the call to atof() below */
#include <math.h>
/* need this for printf(), fopen() and stdin below */
#include <stdio.h>
%}

DIGIT    [0-9]
ID       [a-z][a-z0-9]*
%%

{DIGIT}+    {
                       printf("An integer: %s (%d)\n", yytext,
                       atoi(yytext));
                       }

{DIGIT}+"."{DIGIT}*    {
                       printf("A float: %s (%g)\n", yytext,
                       atof(yytext));
                       }

if|then|begin|end|procedure|function        {
                       printf("A keyword: %s\n", yytext);
                       }

{ID}                   printf("An identifier: %s\n", yytext);

"+"|"-"|"*"|"/"        printf("An operator: %s\n", yytext);

"{"[^}\n]*"}"         /* eat up one-line comments */

[ \t\n]+               /* eat up white space */

.                      printf("Unrecognized character: %s\n", yytext);

%%

int main(int argc, char *argv[ ])
{
                      ++argv, --argc;  /* skip over program name */
                      if (argc > 0)
                          yyin = fopen(argv[0], "r");
                      else
                      yyin = stdin;
    
                      yylex();
}

Environment Variables

See environ(5) for descriptions of the following environment variables that affect the execution of lex: LANG, LC_ALL, LC_COLLATE, LC_CTYPE, LC_MESSAGES, and NLSPATH.

Exit Status

The following exit values are returned:

0

Successful completion.

>0

An error occurred.

Attributes

See attributes(5) for descriptions of the following attributes:

ATTRIBUTE TYPE
ATTRIBUTE VALUE
Availability
SUNWbtool
Interface Stability
Standard

See Also

yacc(1), attributes(5), environ(5), regex(5), standards(5)

Notes

If routines such as yyback(), yywrap(), and yylock() in .l (ell) files are to be external C functions, the command line to compile a C++ program must define the __EXTERN_C__ macro. For example:

example%  CC –D__EXTERN_C__ ... file