# DSL variables

Miller has the following kinds of variables:

**Fields of stream records**, accessed using the `$` prefix. These refer to fields of the current data-stream record. For example, in `echo x=1,y=2 | mlr put '$z = $x + $y'`, `$x` and `$y` refer to input fields, and `$z` refers to a new, computed output field. In the following contexts, you can refer to the entire record as `$*`.

**Out-of-stream variables** accessed using the `@` prefix. These refer to data that persists from one record to the next, including in `begin` and `end` blocks (which execute before/after the record stream is consumed, respectively). You use them to remember values across records, such as sums, differences, and counters, among other things.  In the following contexts, you can refer to the entire out-of-stream-variables collection as `@*`.

**Local variables** are limited in scope and extent to the current statements being executed, including function arguments, bound variables in for loops, and local variables.

**Built-in variables** such as `NF`, `NR`, `FILENAME`, `M_PI`, and `M_E`.  These are all capital letters and are read-only (although some of them change value from one record to another).

**Keywords** are not variables, but since their names are reserved, you cannot use these names for local variables.

## Field names

Names of fields within stream records must be specified using a `$` in [filter and put expressions](reference-dsl.md), even though the dollar signs don't appear in the data stream itself. For integer-indexed data, this looks like `awk`'s `$1,$2,$3`, except that Miller allows non-numeric names such as `$quantity` or `$hostname`.  Likewise, enclose string literals in double quotes in `filter` expressions even though they don't appear in file data.  In particular, `mlr filter '$x=="abc"'` passes through the record `x=abc`.

If field names have **special characters** such as `.`, then you can use braces, e.g. `'${field.name}'`.

You may also use a **computed field name** in square brackets, e.g.

GENMD-RUN-COMMAND
echo a=3,b=4 | mlr filter '$["x"] < 0.5'
GENMD-EOF

GENMD-RUN-COMMAND
echo s=green,t=blue,a=3,b=4 | mlr put '$[$s."_".$t] = $a * $b'
GENMD-EOF

Notes:

The names of record fields depend on the contents of your input data stream, and their values change from one record to the next as Miller scans through your input data stream.

Their **extent** is limited to the current record; their **scope** is the `filter` or `put` command in which they appear.

These are **read-write**: you can do `$y=2*$x`, `$x=$x+1`, etc.

Records are Miller's output: field names present in the input stream are passed through to output (written to standard output) unless fields are removed with `cut`, or records are excluded with `filter` or `put -q`, etc. Simply assign a value to a field, and it will be output.

## Positional field names

Even though Miller's main selling point is name-indexing, sometimes you really want to refer to a field name by its positional index (starting from 1).

Use `$[[3]]` to access the name of field 3.  More generally, any expression evaluating to an integer can go between `$[[` and `]]`.

Then, using a computed field name, `$[ $[[3]] ]` is the value in the third field. This has the shorter equivalent notation `$[[[3]]]`.

GENMD-RUN-COMMAND
mlr cat data/small
GENMD-EOF

GENMD-RUN-COMMAND
mlr put '$[[3]] = "NEW"' data/small
GENMD-EOF

GENMD-RUN-COMMAND
mlr put '$[[[3]]] = "NEW"' data/small
GENMD-EOF

GENMD-RUN-COMMAND
mlr put '$NEW = $[[NR]]' data/small
GENMD-EOF

GENMD-RUN-COMMAND
mlr put '$NEW = $[[[NR]]]' data/small
GENMD-EOF

GENMD-RUN-COMMAND
mlr put '$[[[NR]]] = "NEW"' data/small
GENMD-EOF

Right-hand side accesses to non-existent fields -- i.e., with index less than 1 or greater than `NF` -- return an absent value. Likewise, left-hand side accesses only refer to fields that already exist. For example, if a field has 5 records, then assigning the name or value of the 6th (or 600th) field results in a no-op.

GENMD-RUN-COMMAND
mlr put '$[[6]] = "NEW"' data/small
GENMD-EOF

GENMD-RUN-COMMAND
mlr put '$[[[6]]] = "NEW"' data/small
GENMD-EOF

!!! note

    You can use positional field names only in the [Miller DSL](reference-dsl.md), i.e., only with the verbs `put` and `filter`.

## Out-of-stream variables

These are prefixed with an at-sign, e.g., `@sum`.  Furthermore, unlike built-in variables and stream-record fields, they are maintained in an arbitrarily nested map: you can do `@sum += $quantity`, or `@sum[$color] += $quantity`, or `@sum[$color][$shape] += $quantity`. The keys for the multi-level map can be any expression that evaluates to string or integer: e.g.  `@sum[NR] = $a + $b`, `@sum[$a."-".$b] = $x`, etc.

Their names and their values are entirely under your control; they change only when you assign them.

Just as for field names in stream records, if you want to define out-of-stream variables with **special characters** such as `.` then you can use braces, e.g. `'@{variable.name}["index"]'`.

You may use a **computed key** in square brackets, e.g.

GENMD-RUN-COMMAND
echo s=green,t=blue,a=3,b=4 | mlr put -q '@[$s."_".$t] = $a * $b; emit all'
GENMD-EOF

Out-of-stream variables are **scoped** to the `put` command in which they appear.  In particular, if you have two or more `put` commands separated by `then`, each put will have its own set of out-of-stream variables:

GENMD-RUN-COMMAND
cat data/a.dkvp
GENMD-EOF

GENMD-RUN-COMMAND
mlr put '@sum += $a; end {emit @sum}' \
  then put 'is_present($a) {$a=10*$a; @sum += $a}; end {emit @sum}' \
  data/a.dkvp
GENMD-EOF

Out-of-stream variables' **extent** is from the start to the end of the record stream, i.e., every time the `put` or `filter` statement referring to them is executed.

Out-of-stream variables are **read-write**: you can do `$sum=@sum`, `@sum=$sum`, etc.

## Indexed out-of-stream variables

Using an index on the `@count` and `@sum` variables, we get the benefit of the `-g` (group-by) option, which `mlr stats1` and various other Miller commands have:

GENMD-RUN-COMMAND
mlr put -q '
  @x_count[$a] += 1;
  @x_sum[$a] += $x;
  end {
    emit @x_count, "a";
    emit @x_sum, "a";
  }
' ./data/small
GENMD-EOF

GENMD-RUN-COMMAND
mlr stats1 -a count,sum -f x -g a ./data/small
GENMD-EOF

Indices can be arbitrarily deep -- here there are two or more of them:

GENMD-RUN-COMMAND
mlr --from data/medium put -q '
  @x_count[$a][$b] += 1;
  @x_sum[$a][$b] += $x;
  end {
    emit (@x_count, @x_sum), "a", "b";
  }
'
GENMD-EOF

The idea is that `stats1`, and other Miller verbs, encapsulate frequently-used patterns with a minimum of keystroking (and run a little faster), whereas using out-of-stream variables you have more flexibility and control in what you do.

Begin/end blocks can be mixed with pattern/action blocks. For example:

GENMD-RUN-COMMAND
mlr put '
  begin {
    @num_total = 0;
    @num_positive = 0;
  };
  @num_total += 1;
  $x > 0.0 {
    @num_positive += 1;
    $y = log10($x); $z = sqrt($y)
  };
  end {
    emitf @num_total, @num_positive
  }
' data/put-gating-example-1.dkvp
GENMD-EOF

## Local variables

Local variables are similar to out-of-stream variables, except that their extent is limited to the expressions in which they appear (and their basenames can't be computed using square brackets). There are three kinds of local variables: **arguments** to functions/subroutines, **variables bound within for-loops**, and **locals** defined within control blocks. They may be untyped using `var`, or typed using `num`, `int`, `float`, `str`, `bool`, `arr`, `map`, and `funct`.

For example:

GENMD-RUN-COMMAND
# Here I'm using a specified random-number seed, so this example always
# produces the same output for this web document: in everyday practice, we
# would leave off the --seed 12345 part.
mlr --seed 12345 seqgen --start 1 --stop 10 then put '
  func f(a, b) {                          # function arguments a and b
      r = 0.0;                            # local r scoped to the function
      for (int i = 0; i < 6; i += 1) {    # local i scoped to the for-loop
          num u = urand();                # local u scoped to the for-loop
          r += u;                         # updates r from the enclosing scope
      }
      r /= 6;
      return a + (b - a) * r;
  }
  num o = f(10, 20);                      # local to the top-level scope
  $o = o;
'
GENMD-EOF

Things which are completely unsurprising, resembling many other languages:

* Parameter names are bound to their arguments but can be reassigned, e.g., if there is a parameter named `a`, then you can reassign the value of `a` to be something else within the function if you like.

* However, you cannot redeclare the *type* of an argument or a local: `var a=1; var a=2` is an error but `var a=1;  a=2` is OK.

* All argument-passing is positional rather than by name; arguments are passed by value, not by reference. (This is also true for map-valued variables: they are not, and cannot be, passed by reference.)

* You can define locals (using `var`, `num`, etc.) at any scope (if-statements, else-statements, while-loops, for-loops, or the top-level scope), and nested scopes will have access (more details on scope in the next section).  If you define a local variable with the same name inside an inner scope, then a new variable is created with the narrower scope.

* If you assign to a local variable for the first time in a scope without declaring it as `var`, `num`, etc. then: if it exists in an outer scope, that outer-scope variable will be updated; if not, it will be defined in the current scope as if `var` had been used. (See also [Type-checking](reference-dsl-variables.md#type-checking) for an example.) I recommend always declaring variables explicitly to make the intended scoping clear.

* Functions and subroutines never have access to locals from their callee (unless passed by value as arguments).

Things which are perhaps surprising compared to other languages:

* Type declarations using `var`, or typed using `num`, `int`, `float`, `str`, `bool`, `arr`, `map`, `funct`, are not necessary to declare local variables.  Function arguments and variables bound in for-loops over stream records and out-of-stream variables are *implicitly* declared using `var`. (Some examples are shown below.)

* Type-checking is done at assignment time. For example, `float f = 0` is an error (since `0` is an integer), as is `float f = 0.0; f = 1`. For this reason, I prefer to use `num` over `float` in most contexts, as `num` encompasses both integer and floating-point values. For more information, refer to [Type-checking](reference-dsl-variables.md#type-checking).

* Bound variables in for-loops over stream records and out-of-stream variables are implicitly local to that block. E.g. in `for (k, v in $*) { ... }` `for ((k1, k2), v in @*) { ... }` if there are `k`, `v`, etc. in the enclosing scope then those will be masked by the loop-local bound variables in the loop, and moreover the values of the loop-local bound variables are not available after the end of the loop.

* For C-style triple-for loops, if a for-loop variable is defined using `var`, `int`, etc., then it is scoped to that for-loop. E.g. `for (i = 0; i < 10; i += 1) { ... }` and `for (int i = 0; i < 10; i += 1) { ... }`. (This is unsurprising.). If there is no typedecl and an outer-scope variable of that name exists, then it is used. (This is also unsurprising.) But if there is no outer-scope variable of that name, then the variable is scoped to the for-loop only.

The following example demonstrates the scope rules:

GENMD-RUN-COMMAND
cat data/scope-example.mlr
GENMD-EOF

GENMD-RUN-COMMAND
cat data/scope-example.dat
GENMD-EOF

GENMD-RUN-COMMAND
mlr --oxtab --from data/scope-example.dat put -f data/scope-example.mlr
GENMD-EOF

And this example demonstrates the type-declaration rules:

GENMD-RUN-COMMAND
cat data/type-decl-example.mlr
GENMD-EOF

## Map literals

Miller's `put`/`filter` DSL has four kinds of maps. **Stream records** are (single-level) maps from name to value. **Out-of-stream variables** and **local variables** can also be maps, although they can be multi-level maps (e.g. `@sum[$x][$y]`).  The fourth kind is **map literals**. These cannot be on the left-hand side of assignment expressions. Syntactically, they look like JSON, although Miller allows string and integer keys in its map literals while JSON allows only string keys (e.g., `"3"` rather than `3`). Note, though, that integer keys become stringified in Miller: `@mymap[3]=4` results in `@mymap` being `{"3":4}`.

For example, the following swaps the input stream's `a` and `i` fields, modifies `y`, and drops the rest:

GENMD-RUN-COMMAND
mlr --opprint put '
  $* = {
    "a": $i,
    "i": $a,
    "y": $y * 10,
  }
' data/small
GENMD-EOF

Likewise, you can assign map literals to out-of-stream variables or local variables; pass them as arguments to user-defined functions, return them from functions, and so on:

GENMD-RUN-COMMAND
mlr --from data/small put '
  func f(map m): map {
    m["x"] *= 200;
    return m;
  }
  $* = f({"a": $a, "x": $x});
'
GENMD-EOF

Like out-of-stream and local variables, map literals can be multi-level:

GENMD-RUN-COMMAND
mlr --from data/small put -q '
  begin {
    @o = {
      "nrec": 0,
      "nkey": {"numeric":0, "non-numeric":0},
    };
  }
  @o["nrec"] += 1;
  for (k, v in $*) {
    if (is_numeric(v)) {
      @o["nkey"]["numeric"] += 1;
    } else {
      @o["nkey"]["non-numeric"] += 1;
    }
  }
  end {
    dump @o;
  }
'
GENMD-EOF

See also the [Maps page](reference-main-maps.md).

## Built-in variables

These are written all in capital letters, and only a small, specific set of them is defined by Miller.

Namely, Miller supports the following five built-in variables for [filter and
put](reference-dsl.md), all `awk`-inspired: `NF`, `NR`, `FNR`, `FILENUM`, and
`FILENAME`, as well as the mathematical constants `M_PI` and `M_E`.  As well,
there are the read-only separator variables `IRS`, `ORS`, `IFS`, `OFS`, `IPS`,
and `OPS` as discussed on the [separators page](reference-main-separators.md),
and the flatten/unflatten separator `FLATSEP` discussed on the
[flatten/unflatten page](flatten-unflatten.md).  Lastly, the `ENV` map allows
read/write access to environment variables, e.g., `ENV["HOME"]` or
`ENV["foo_".$hostname]` or `ENV["VERSION"]="1.2.3"`.

<!--- TODO: FLATSEP IFLATSEP OFLATSEP --->

GENMD-RUN-COMMAND
mlr filter 'FNR == 2' data/small*
GENMD-EOF

GENMD-RUN-COMMAND
mlr put '$fnr = FNR' data/small*
GENMD-EOF

Their values of `NF`, `NR`, `FNR`, `FILENUM`, and `FILENAME` change from one
record to the next as Miller scans through your input data stream. The
mathematical constants, of course, do not change; `ENV` is populated from the
system environment variables at the time Miller starts. Any changes made to
`ENV` by assigning to it will affect any subprocesses, such as using
[piped tee](reference-dsl-output-statements.md#redirected-output-statements).

Their **scope is global**: you can refer to them in any `filter` or `put` statement. The input-record reader assigns their values:

GENMD-RUN-COMMAND
mlr --csv put '$nr = NR' data/a.csv
GENMD-EOF

GENMD-RUN-COMMAND
mlr --csv repeat -n 3 then put '$nr = NR' data/a.csv
GENMD-EOF

The **extent** is for the duration of the put/filter: in a `begin` statement (which executes before the first input record is consumed) you will find `NR=1` and in an `end` statement (which is executed after the last input record is consumed) you will find `NR` to be the total number of records ingested.

These are all **read-only** for the `mlr put` and `mlr filter` DSL: they may be assigned from, e.g., `$nr=NR`, but they may not be assigned to: `NR=100` is a syntax error.

## Type-checking

Miller's `put`/`filter` DSL supports two optional kinds of type-checking.  One is inline **type tests** and **type assertions** within expressions.  The other is **type declarations** for assignments to local variables, binding of arguments to user-defined functions, and return values from user-defined functions. These are discussed in the following subsections.

Use of type-checking is entirely up to you: omit it if you want flexibility with heterogeneous data; use it if you want to help catch misspellings in your DSL code or unexpected irregularities in your input data.

### Type-test and type-assertion expressions

The following `is_...` functions take a value and return a boolean indicating whether the argument is of the indicated type. The `assert_...` functions return their argument if it is of the specified type, and cause a fatal error otherwise:

GENMD-RUN-COMMAND
mlr -f | grep ^is
GENMD-EOF

GENMD-RUN-COMMAND
mlr -f | grep ^assert
GENMD-EOF

See [Data-cleaning Examples](data-cleaning-examples.md) for examples of how to use these.

### Type declarations for local variables, function parameters, and function return values

Local variables can be defined either untyped as in `x = 1`, or typed as in `int x = 1`. Types include **var** (explicitly untyped), **int**, **float**, **num** (int or float), **str**, **bool**, **arr**, **map**, and **funct**. These optional type declarations are enforced at the time values are assigned to variables: whether at the initial value assignment as in `int x = 1` or in any subsequent assignments to the same variable farther down in the scope.

The reason for `num` is that `int` and `float` typedecls are very precise:

GENMD-CARDIFY
float a = 0;   # Runtime error since 0 is int, not float
int   b = 1.0; # Runtime error since 1.0 is float, not int
num   c = 0;   # OK
num   d = 1.0; # OK
GENMD-EOF

A suggestion is to use `num` for general use when you want numeric content, and use `int` when you genuinely want integer-only values, e.g., in loop indices or map keys (since Miller map keys can only be strings or ints).

The `var` type declaration indicates no type restrictions, e.g., `var x = 1` has the same type restrictions on `x` as `x = 1`. The difference is in intentional shadowing: if you have `x = 1` in outer scope and `x = 2` in inner scope (e.g., within a for-loop or an if-statement) then outer-scope `x` has value 2 after the second assignment.  But if you have `var x = 2` in the inner scope, then you are declaring a variable scoped to the inner block.) For example:

GENMD-CARDIFY
x = 1;
if (NR == 4) {
  x = 2; # Refers to outer-scope x: value changes from 1 to 2.
}
print x; # Value of x is now two
GENMD-EOF

GENMD-CARDIFY
x = 1;
if (NR == 4) {
  var x = 2; # Defines a new inner-scope x with value 2
}
print x;     # Value of this x is still 1
GENMD-EOF

Likewise, function arguments can optionally be typed, with type enforced when the function is called:

GENMD-CARDIFY
func f(map m, int i) {
  ...
}
$a = f({1:2, 3:4}, 5);     # OK
$b = f({1:2, 3:4}, "abc"); # Runtime error
$c = f({1:2, 3:4}, $x);    # Runtime error for records with non-integer field named x
if (NR == 4) {
  var x = 2; # Defines a new inner-scope x with value 2
}
print x;     # Value of this x is still 1
GENMD-EOF

Thirdly, function return values can be type-checked at the point of `return` using `:` and a typedecl after the parameter list:

GENMD-CARDIFY
func f(map m, int i): bool {
  ...
  ...
  if (...) {
    return "false"; # Runtime error if this branch is taken
  }
  ...
  ...
  if (...) {
    return retval; # Runtime error if this function doesn't have an in-scope
    # boolean-valued variable named retval
  }
  ...
  ...
  # In Miller, if your functions don't explicitly return a value, they return absent-null.
  # So it would also be a runtime error on reaching the end of this function without
  # an explicit return statement.
}
GENMD-EOF

The `funct` keyword, for _function type_, indicates that a variable, argument, or return value is a function -- either a [function literal](reference-dsl-user-defined-functions.md#function-literals) or a (named) [user-defined function](reference-dsl-user-defined-functions.md).

GENMD-CARDIFY
$ cat funct-example.mlr
func makefunc(): funct {
  return func(x,y) {
    return 10*x + y
  }
}

func callfunc(funct f, num x, num y): num {
  return f(x, y)
}
GENMD-EOF

GENMD-CARDIFY
$ rlwrap mlr repl
Miller 6.0.0-dev REPL for darwin/amd64/go1.17
Docs: https://miller.readthedocs.io
Type ':h' or ':help' for online help; ':q' or ':quit' to quit.

[mlr] :load funct-example.mlr

[mlr] f = makefunc()

[mlr] f
function-literal-000001

[mlr] f(2,3)
23

[mlr] callfunc(f, 3, 5)
35
GENMD-EOF

## Aggregate variable assignments

There are three remaining kinds of variable assignment using out-of-stream variables, the last two of which use the `$*` syntax:

* Recursive copy of out-of-stream variables
* Out-of-stream variable assigned to full stream record
* Full stream record assigned to an out-of-stream variable

Example recursive copy of out-of-stream variables:

GENMD-RUN-COMMAND
mlr --opprint --from data/small put -q '
  @v["sum"] += $x;
  @v["count"] += 1;
  end{
    dump;
    @w = @v;
    dump
  }
'
GENMD-EOF

Example of an out-of-stream variable assigned to the full stream record, where the 2nd record is stashed, and the 4th record is overwritten with that:

GENMD-RUN-COMMAND
mlr put 'NR == 2 {@keep = $*}; NR == 4 {$* = @keep}' data/small
GENMD-EOF

Example of full stream record assigned to an out-of-stream variable, finding the record for which the `x` field has the largest value in the input stream:

GENMD-RUN-COMMAND
cat data/small
GENMD-EOF

GENMD-RUN-COMMAND
mlr --opprint put -q '
  is_null(@xmax) || $x > @xmax {@xmax = $x; @recmax = $*};
  end {emit @recmax}
' data/small
GENMD-EOF

## Keywords for filter and put

GENMD-RUN-COMMAND
mlr help list-keywords # you can also use mlr -k
GENMD-EOF


GENMD-RUN-COMMAND
mlr help usage-keywords # you can also use mlr -K
GENMD-EOF
