io - input/output
Enable with use io;. Formatted output with printf (stdout), eprintf (stderr) and sprintf (to a string), which share a Go-style format-string mini-language; and stdin input: readLine / readLines / eof for lines, readBytes / readChars for binary and fixed-size reads.
printf
Writes formatted output to standard output. Two calling shapes: a format string alone, or a format string and its arguments. The first argument is always the format: a single non-string value (io.printf($x)) is an error naming "%v" (removed in 0.28.0); write io.printf("%v", $x) (jennifer lint L302 points at each use). The same holds for sprintf and eprintf.
io.printf("hi\n"); # literal string (no verbs)
io.printf("you are %d years old!\n", $age); # format string + arguments
io.printf("%s = %d, ok=%t\n", "answer", 42, true);Never pass a dynamic string as the format argument. A single string argument is always the format string, so
io.printf(s)scanssfor verbs. That is safe only for a string you wrote. For any value you did not author (a generated password, user input, file contents), useio.printf("%s", s)(or"%s\n"). A stray%in the data would otherwise be read as a verb:%cfails as an unknown verb,%sas a missing argument, soio.printf(password)is a latent bug. There is no separate verbatim-print builtin (see technical/rejected.md);printf("%s", s)is the one canonical way to print a dynamic string. String interpolation counts:io.printf("{$name}\n")makes$namepart of the format. Writeio.printf("%s\n", $name).
eprintf
Like printf (same argument forms and verbs), but writes to standard error. Use it for diagnostics, warnings, and logs that must not mix into a program's stdout data.
io.eprintf("warning: retrying (%d/%d)\n", $attempt, $max); # goes to stderrsprintf
Same arguments as printf but returns the formatted string instead of writing it.
def msg as string init io.sprintf("%d + %d = %d", 1, 2, 3);
io.printf("%s\n", $msg); # "1 + 2 = 3"Format verbs
| Verb | Required kind | Notes |
|---|---|---|
%d | int | decimal |
%f | float | shortest round-trip |
%s | string | raw |
%t | bool | true / false |
%v | any | uses the value's display form |
%a | list / map | aggregate, literal-like shape (see %a modifiers) |
%% | - | literal % |
Mismatches (wrong verb for the value kind, too few or too many args, dangling %, unknown verb) all produce runtime errors.
Escaping the meta-characters:
- A literal
%in any string passed toprintf/sprintfmust be doubled to%%. - A literal
|immediately after a verb must be doubled to||, because|otherwise starts a modifier list (see Format modifiers). The escape consumes one of the two|s; the other appears in the output. Pipes that don't touch a verb are normal characters and need no escaping:io.printf("a|b %s||c|d\n", "X")printsa|b X|c|d: the||after%sis the escape, while the|s ina|bandc|dsit between non-verb characters and pass through unchanged.
Format modifiers
Each verb (except %v) accepts an optional pipe-separated modifier list:
%verb[|key=value]*Modifiers are order-independent flags: %d|pad=5|fill=0|align=right and %d|align=right|fill=0|pad=5 produce the same output. The list runs left-to-right until it hits a byte that isn't part of a key or value. A bare value is either a word (letters, digits, and _, with an optional leading - before a digit) or exactly one separator character (, . - :, the %d|sep= set). So punctuation written right after a modifier is ordinary text: "0x%d|base=16, %d" prints 0xff, 7, and "%f|prec=2." ends a sentence with the number. A value that needs any other character is written double-quoted (%a|sep=" | "). A literal | immediately after a verb is written || (see escaping the meta-characters above). Unknown keys, bad values, missing companions (e.g. group= without sep=), and the same key set twice are all runtime errors. An integer value (pad, max, prec, group, depth) above 4096 is an error of kind "limit".
Evaluation order within one verb:
- Null check. If the value is
nulland the spec includes anull=modifier, the verb-specific render is skipped and the configured replacement is used. - Verb-specific render.
mode,base,prec,sci,sign,group/sep,caseapply here. - Layout.
maxtruncates (rune-aware), thenpad+fill+alignextends. Layout still applies to the null replacement, so columns line up.
null= (shared by %s, %d, %f, %t)
| Form | Output when value is null |
|---|---|
null=empty | "" |
null=null | "null" |
null=literal("X") | X: the quoted text, with Jennifer string escapes parsed |
Without a null= modifier, a null value is still a type-mismatch error against any verb except %v. null= wins over every other modifier on its verb: %s|mode=quote|null=literal("X") on a null prints X, not "X".
%s modifiers
| Key | Values | Default | Effect |
|---|---|---|---|
pad | non-negative integer | - | minimum rune width |
max | non-negative integer | - | truncate to N runes |
align | left, right, center | left | which side gets the pad spaces; center splits the pad evenly (odd leftover goes right) |
mode | raw, quote, escape | raw | wrap in "..." (quote) / show escapes (escape) |
null | see above | - | substitute when value is null |
mode=quote wraps the string in double quotes and escapes interior \, ", and control bytes. mode=escape does the same escaping without the wrapping, to show a string's structure in debug output.
io.printf("[%s|pad=8|align=right]\n", "hi"); # [ hi]
io.printf("[%s|max=3]\n", "abcdef"); # [abc]
io.printf("%s|mode=quote\n", "a\nb"); # "a\nb"%d modifiers
| Key | Values | Default | Effect |
|---|---|---|---|
pad | non-negative integer | - | minimum width |
fill | 0 | space | zero-pad between sign and digits; requires align=right (the default) |
align | left, right | right | which side gets the pad |
base | 2, 8, 10, 16 | 10 | digit base; hex uses lowercase |
sign | negative, always, space | negative | sign for non-negative values |
group | positive integer | - | digit-group size, reading right-to-left |
sep | one of _, ,, ., -, : | - | group separator; required with group= and vice versa |
null | see above | - | substitute when value is null |
io.printf("%d|base=2\n", 5); # 101
io.printf("%d|base=16|group=4|sep=_\n", 3735928559); # dead_beef
io.printf("%d|pad=5|fill=0|sign=always\n", 42); # +0042%f modifiers
| Key | Values | Default | Effect |
|---|---|---|---|
prec | non-negative integer | shortest | fraction digits (or mantissa fraction digits when sci=true) |
trim | true, false | false | strip trailing fraction zeros and the . if all zero |
sci | true, false | false | force scientific notation (1.23e+03) |
pad | non-negative integer | - | minimum width |
fill | 0 | space | zero-pad between sign and digits; requires align=right (the default) |
align | left, right | right | which side gets the pad |
sign | negative, always, space | negative | sign for non-negative values |
group | positive integer | - | digit-group size of the integer part, reading right-to-left |
sep | one of _, ,, ., -, : | - | group separator; required with group= and vice versa |
null | see above | - | substitute when value is null |
fill, group and sep work as on %d, on the digits before the . (the mantissa's under sci=true, which has one, so grouping leaves it alone); the fraction and exponent count towards pad. As in C, -0.0 keeps its minus, and NaN and infinity are padded with spaces even with fill=0.
prec rounds the shortest decimal that reads back as the float (what %f prints without prec), half to even, as intl.formatNumber and decimal.round do: 1002.675 is 1002.68 at prec=2 (its binary value is 1002.67499...), 2.345 is 2.34 and 2.5 at prec=0 is 2.
io.printf("%f|prec=2\n", 3.14159); # 3.14
io.printf("%f|prec=4|trim=true\n", 3.0); # 3
io.printf("%f|sci=true|prec=2\n", 0.00123); # 1.23e-03
io.printf("%f|prec=3|pad=10|fill=0|sign=always\n", 3.14159); # +00003.142 (C's %+010.3f)
io.printf("%f|prec=2|group=3|sep=,\n", 1234567.891); # 1,234,567.89
io.printf("%f|sci=true|prec=3|pad=12|fill=0\n", 1234.5); # 0001.234e+03%t modifiers
| Key | Values | Default | Effect |
|---|---|---|---|
case | lower, upper, title | lower | true/false, TRUE/FALSE, True/False |
null | see above | - | substitute when value is null |
%v modifiers
%v takes no modifiers: it is the "print it as is" verb. Use a typed verb plus modifiers to shape the output.
%a modifiers
%a is the aggregate verb: it renders a list or map in literal-like shape, recursing into nested aggregates. Non-collection input is a runtime error.
| Key | Values | Default | Effect |
|---|---|---|---|
sep | quoted string | ", " | element separator (between list items, between map entries) |
kv | quoted string | ": " | key/value separator for map entries |
open | quoted string | [ (list) / { (map) | opening bracket |
close | quoted string | ] (list) / } (map) | closing bracket |
depth | non-negative integer | unlimited | max recursion depth; deeper levels collapse to [...] / {...} (depth=0 collapses at the top) |
null | skip | - | omit null list elements and null map values |
Element modifiers. %a also accepts the presentation modifiers of the typed verbs. Each applies to every scalar of its kind inside the aggregate, at any depth, with the same values and meaning as on that verb:
| Key | Applies to | Same as on |
|---|---|---|
prec | float elements | %f |
trim | float elements | %f |
sci | float elements | %f |
base | int elements | %d |
sign | int and float elements | %d / %f |
mode | string elements, map keys included | %s |
case | bool elements | %t |
Elements of any other kind (structs, enums, opaque values, null) render as %v would. sep keeps its %a meaning (the element separator), so digit grouping (group) is not available inside %a; neither are the layout modifiers pad, align, max, and fill, which shape a whole field rather than each element.
Modifier values can be double-quoted to include spaces, brackets, or other characters reserved by the modifier-list grammar. The escape set is the standard \n \r \t \\ \":
def xs as list of int init [1, 2, 3];
io.printf("%a\n", $xs); # [1, 2, 3]
io.printf("%a|sep=\" | \"\n", $xs); # 1 | 2 | 3 (with brackets)
io.printf("%a|open=\"<\"|close=\">\"\n", $xs); # <1, 2, 3>
def grid as list of list of int init [[1, 2], [3, 4]];
io.printf("%a\n", $grid); # [[1, 2], [3, 4]]
io.printf("%a|depth=1\n", $grid); # [[...], [...]]
def m as map of string to int init {"a": 1, "b": 2};
io.printf("%a\n", $m); # {a: 1, b: 2}
io.printf("%a|kv=\"=\"|sep=\" \"\n", $m); # {a=1 b=2}
def inverse as list of list of float init [[0.6000000000000001, -0.7], [-0.2, 0.4]];
io.printf("%a|prec=10|trim=true\n", $inverse); # [[0.6, -0.7], [-0.2, 0.4]]
io.printf("%a|base=16\n", [255, 4096]); # [ff, 1000]
io.printf("%a|mode=quote\n", {"k": "v"}); # {"k": "v"}Without an element modifier, each element renders in the same display form as %v. null=skip is only valid on %a: it omits null elements entirely; the other null= modes (empty, null, literal) are rejected for %a because they have no sensible per-element meaning.
Input from stdin
Builtins for reading standard input: a line (or n bytes / runes) at a time, with an explicit end-of-input predicate.
All of them, and term's readByte / readByteTimeout, read through one shared stdin buffer, so io and term reads can be mixed: each byte goes to exactly one read, in input order, a byte a timed-out term.readByteTimeout was waiting for is the next byte io.readLine sees, and the end of input (or a read error) reached by either is seen by both. io reads from concurrent spawn tasks take turns, a whole call at a time, and no byte is ever returned twice.
io.readLine() -> string
Read one line from stdin. The trailing \r\n or \n is stripped; the returned string never carries a newline. Calling at end-of-input is a positioned runtime error (io.readLine: end of input), so the caller must check io.eof() first.
A final line that has no trailing newline is returned normally on the call that reaches it; the subsequent call errors. A line over 256 MiB (32 MiB on jennifer-tiny) is a catchable error of kind "limit" (io.readLine: line exceeds the 268435456-byte limit). That error consumes only the bytes read up to the cap: the next call continues the same line, so a caller that skips such a line calls readLine again until a call does not throw "limit" (that call reads the line's tail). A line that is not valid UTF-8 is consumed and is a catchable error of kind "io" with the offset of the first bad byte in the line (io.readLine: invalid UTF-8 at byte 2); read binary input with io.readBytes.
io.readLine(prompt) -> string
Same as io.readLine() but writes prompt to stdout (no newline added) before reading. The prompt is written unconditionally, even when stdin is piped (it is not silently skipped off a non-TTY).
def name as string init io.readLine("name: ");
io.printf("hi, %s\n", $name);io.eof() -> bool
True if and only if the next io.readLine() (or io.readBytes / io.readChars) would return less than requested. Implemented by peeking one byte through a buffered reader; the byte stays in the buffer for the next read. Once true, io.eof() stays true for the rest of the run.
io.readBytes(n) -> bytes
Reads n bytes from stdin (fewer at end of input) and returns them as a bytes value. If EOF is hit before n bytes are available, returns the partial result and io.eof() becomes true on the next call. n must be a non-negative int, at most 256 MiB (32 MiB on jennifer-tiny; past it an error of kind "limit"); the buffer grows with the data read, so a large n on a short stream costs only what arrives.
use io;
def first as bytes init io.readBytes(8); # 8 bytes, fewer at end of input
io.printf("got %d bytes\n", len($first));io.readLines() -> list of string
Reads every remaining line from stdin and returns them as a list of string, each with its trailing newline stripped: the slurp counterpart to the streaming readLine() + eof() loop, for tiny filter scripts over bounded input. Line splitting is OS-independent: it breaks on \n and strips a \r only when it precedes that \n (a CRLF terminator), so LF and CRLF input read the same on any platform, while a bare \r that is not part of a CRLF is kept as data (exactly like readLine). Empty stdin yields an empty list; a blank line is preserved as ""; a final line with no trailing newline is included.
It reads the whole input into memory, one value per line, so a few million short lines is already hundreds of MB. More than 256 MiB of input or 4194304 lines (32 MiB / 262144 on jennifer-tiny) is a catchable error of kind "limit" naming the limit. Budget readLines() for small inputs (low single-digit MB); for large or untrusted streams keep the streaming readLine() loop, which stays flat in memory. Shares one buffered stdin reader with readLine / readBytes / readChars (and term's key reads), so it returns only the lines not already consumed. Refused inside the REPL. Input that is not valid UTF-8 is an error of kind "io" with the byte offset within this call's read and the line number (io.readLines: invalid UTF-8 at byte 6 (line 3)); use io.readBytes for binary input.
use io;
def lines as list of string init io.readLines();
io.printf("read %d line(s)\n", len($lines));io.readChars(n) -> string
Reads n Unicode code points from stdin (fewer at end of input), decoded from UTF-8, and returns them as a string. Same EOF behavior as readBytes (partial result, sticky io.eof()). n is a rune count, not a byte count; one Unicode character can be 1-4 bytes wide. n above 64 Mi (8 Mi on jennifer-tiny) is an error of kind "limit". An invalid UTF-8 byte (or a rune cut off by EOF) is an error of kind "io" with its offset within this call's read (io.readChars: invalid UTF-8 at byte 3); the bytes before it are consumed. Use io.readBytes for binary input.
use io;
use encoding;
def first as string init io.readChars(3); # 3 runes, fewer at end of input
io.printf("got %d runes (%d bytes)\n", len($first), encoding.lenBytes($first));
# input "h\u00e9llo" prints: got 3 runes (4 bytes)Canonical loop
use io;
while (not io.eof()) {
def line as string init io.readLine();
io.printf("[%s]\n", $line);
}This is the streaming pattern. There is no for line in stdin shortcut, and io.readLine() does not return a sentinel value at EOF: there is one way to read lines. (io.readLines() is the bounded-input slurp, above.)
REPL limitation
The interactive REPL owns stdin via its line editor, so readLine, readLines, readBytes, readChars and eof refuse inside the REPL with a clear error:
io.readLine: stdin is owned by the REPL editorTo try the input functions, put the program in a .j file and run it with stdin piped or redirected: jennifer run prog.j < input.txt.
Errors
| Kind | Raised for |
|---|---|
"io" | stdin text that is not valid UTF-8 in readLine, readLines and readChars |
"limit" | a line, input or count past its cap, a format modifier value above 4096 |
"runtime" | end of input, a read error, a call inside the REPL, and misuse: a wrong argument, a format string that does not match its arguments |
Float display
Floats always display with a decimal point so the value's type stays visible: 5.0 prints as "5.0", not "5". Since / is true division, 4 / 2 is the float 2.0, distinguishable at a glance from an int.
See also: ../user-guide/index.md, ../technical/interpreter.md, index.md.