field reference

The field reference operator

The dollar symbol acts as a unary *field reference operator* and is followed by a number or expression that gives a field number within the [[current_record?]]:

 { print $3 }    # output field number three

Field numbers are not limited to single digits

Unlike the positional parameters in the Unix shell, field numbers are not limited to single digits:

  { print $123 }    # output field number 123

Using a variable name to specify the field number

It is possible to use to use a [[variable_name?]] after the dollar sign to specify the field number:

 { myfield = 4
   print $myfield    # output field number 4
 }

Using an expression to specify the field number

It is also possible to use an [[expression?]] after the dollar sign to specify the field number. Note that parentheses are used around the [[expression?]], to ensure [[evaluation?]] of the [[expression?]] takes precedence over the field reference operator:

 print $(3 + 2)    # output field number 5
 # The parentheses above are important.
 # Without parentheses, we would get a value 2 more than field 3

Referencing a non existent field will produce an empty string

Attempting to reference a non existing field produces an [[empty?]] string.

Referencing field zero gives the entire record

If a value of [[zero?]] is given as the [[argument?]] following the dollar symbol, then the entire record is referenced:

 { print $0 }    # output the entire record

Field numbers must not be negative

It is not permissible to use negative field numbers. Attempting to reference a negative field number will cause [[undefined_behaviour?]], or a [[fatal_error?]] will occur.

Assignment to referenced field

It is possible to change the contents of a field in the current record by making an assignment to the referenced field:

 { $2 = 23 }    # Change field two to a value of 23