mirror of
https://github.com/johnkerl/miller.git
synced 2026-07-18 00:45:47 +00:00
* More mkdocs porting * mkdocs-ify http/external links * move README.md up one level * Further sharpen code-sample CSS * fix last internal-ref links
364 lines
18 KiB
Markdown
364 lines
18 KiB
Markdown
# DSL reference: variables
|
|
|
|
Miller has the following kinds of variables:
|
|
|
|
**Built-in variables** such as `NF`, `NF`, `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).
|
|
|
|
**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 a few contexts, presented below, you can refer to the entire record as `$*`.
|
|
|
|
**Out-of-stream variables** accessed using the `@` prefix. These refer to data which persist 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, counters, and so on. In a few contexts, presented below, 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: these include function arguments, bound variables in for loops, and explicitly declared local variables.
|
|
|
|
**Keywords** are not variables, but since their names are reserved, you cannot use these names for local variables.
|
|
|
|
## Built-in variables
|
|
|
|
These are written all in capital letters, such as `NR`, `NF`, `FILENAME`, 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`. Lastly, the `ENV` hashmap allows read access to environment variables, e.g. `ENV["HOME"]` or `ENV["foo_".$hostname]`.
|
|
|
|
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 and is read-only for the remainder of program execution.
|
|
|
|
Their **scope is global**: you can refer to them in any `filter` or `put` statement. Their values are assigned by the input-record reader:
|
|
|
|
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 fimd.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` DSLs: they may be assigned from, e.g. `$nr=NR`, but they may not be assigned to: `NR=100` is a syntax error.
|
|
|
|
## 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 which 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
|
|
|
|
## 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 hashmap: you can do `@sum += $quanity`, or `@sum[$color] += $quanity`, or `@sum[$color][$shape] += $quanity`. The keys for the multi-level hashmap can be any expression which 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 to 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_INCLUDE_AND_RUN_ESCAPED(data/begin-end-example-6.sh)
|
|
|
|
GENMD_INCLUDE_AND_RUN_ESCAPED(data/begin-end-example-7.sh)
|
|
|
|
Indices can be arbitrarily deep -- here there are two or more of them:
|
|
|
|
GENMD_INCLUDE_AND_RUN_ESCAPED(data/begin-end-example-6a.sh)
|
|
|
|
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_INCLUDE_AND_RUN_ESCAPED(data/begin-end-example-8.sh)
|
|
|
|
## 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`, and `map`.
|
|
|
|
For example:
|
|
|
|
GENMD_INCLUDE_AND_RUN_ESCAPED(data/local-example-1.sh)
|
|
|
|
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`, and `bool` are 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 since `num` encompasses integer and floating-point values. More information is at [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 of 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 hashmaps. **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 hashmaps (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`).
|
|
|
|
For example, the following swaps the input stream's `a` and `i` fields, modifies `y`, and drops the rest:
|
|
|
|
GENMD_INCLUDE_AND_RUN_ESCAPED(data/map-literal-example-1.sh)
|
|
|
|
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_INCLUDE_AND_RUN_ESCAPED(data/map-literal-example-2.sh)
|
|
|
|
Like out-of-stream and local variables, map literals can be multi-level:
|
|
|
|
GENMD_INCLUDE_AND_RUN_ESCAPED(data/map-literal-example-3.sh)
|
|
|
|
By default, map-valued expressions are dumped using JSON formatting. If you use `dump` to print a hashmap with integer keys and you don't want them double-quoted (JSON-style) then you can use `mlr put --jknquoteint`. See also `mlr put --help`.
|
|
|
|
## Type-checking
|
|
|
|
Miller's `put`/`filter` DSLs support 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 parameter, 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**, and **map**. 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
|
|
|
|
## Null data: empty and absent
|
|
|
|
Please see [xxxx](reference-main-null-data.md).
|
|
|
|
## 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 put -q '@v["sum"] += $x; @v["count"] += 1; end{dump; @w = @v; dump}' data/small
|
|
GENMD_EOF
|
|
|
|
Example of out-of-stream variable assigned to 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 usage-keywords
|
|
GENMD_EOF
|
|
|