Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Close D.B.The AWK manual.1995.pdf
Источник:
Скачиваний:
7
Добавлен:
23.08.2013
Размер:
679.83 Кб
Скачать

Chapter 8: Expressions as Action Statements

59

matches = /foo/

will assign either 0 or 1 to the variable matches, depending upon the contents of the current input record.

Constant regular expressions are also used as the rst argument for the sub and gsub functions (see Section 11.3 [Built-in Functions for String Manipulation], page 90).

This feature of the language was never well documented until the posix speci cation.

You may be wondering, when is

$1 ~ /foo/ { : : : }

preferable to

$1 ~ "foo" { : : : }

Since the right-hand sides of both `~' operators are constants, it is more e cient to use the `/foo/' form: awk can note that you have supplied a regexp and store it internally in a form that makes pattern matching more e cient. In the second form, awk must rst convert the string into this internal form, and then perform the pattern matching. The rst form is also better style; it shows clearly that you intend a regexp match.

8.2 Variables

Variables let you give names to values and refer to them later. You have already seen variables in many of the examples. The name of a variable must be a sequence of letters, digits and underscores, but it may not begin with a digit. Case is signi cant in variable names; a and A are distinct variables.

A variable name is a valid expression by itself; it represents the variable's current value. Variables are given new values with assignment operators and increment operators. See Section 8.7 [Assignment Expressions], page 64.

A few variables have special built-in meanings, such as FS, the eld separator, and NF, the number of elds in the current input record. See Chapter 13 [Built-in Variables], page 101, for a list of them. These built-in variables can be used and assigned just like all other variables, but their values are also used or changed automatically by awk. Each built-in variable's name is made entirely of upper case letters.

Variables in awk can be assigned either numeric or string values. By default, variables are initialized to the null string, which is e ectively zero if converted to a number. There is no need to \initialize" each variable explicitly in awk, the way you would in C or most other traditional languages.