Skip to content
Jennifer Programming Language

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.

jennifer
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) scans s for verbs. That is safe only for a string you wrote. For any value you did not author (a generated password, user input, file contents), use io.printf("%s", s) (or "%s\n"). A stray % in the data would otherwise be read as a verb: %c fails as an unknown verb, %s as a missing argument, so io.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 $name part of the format. Write io.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.

jennifer
io.eprintf("warning: retrying (%d/%d)\n", $attempt, $max);   # goes to stderr

sprintf

Same arguments as printf but returns the formatted string instead of writing it.

jennifer
def msg as string init io.sprintf("%d + %d = %d", 1, 2, 3);
io.printf("%s\n", $msg);   # "1 + 2 = 3"

Format verbs

VerbRequired kindNotes
%dintdecimal
%ffloatshortest round-trip
%sstringraw
%tbooltrue / false
%vanyuses the value's display form
%alist / mapaggregate, 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 to printf/sprintf must 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") prints a|b X|c|d: the || after %s is the escape, while the |s in a|b and c|d sit between non-verb characters and pass through unchanged.

Format modifiers

Each verb (except %v) accepts an optional pipe-separated modifier list:

text
%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:

  1. Null check. If the value is null and the spec includes a null= modifier, the verb-specific render is skipped and the configured replacement is used.
  2. Verb-specific render. mode, base, prec, sci, sign, group/sep, case apply here.
  3. Layout. max truncates (rune-aware), then pad+fill+align extends. Layout still applies to the null replacement, so columns line up.

null= (shared by %s, %d, %f, %t)

FormOutput 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

KeyValuesDefaultEffect
padnon-negative integer-minimum rune width
maxnon-negative integer-truncate to N runes
alignleft, right, centerleftwhich side gets the pad spaces; center splits the pad evenly (odd leftover goes right)
moderaw, quote, escaperawwrap in "..." (quote) / show escapes (escape)
nullsee 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.

jennifer
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

KeyValuesDefaultEffect
padnon-negative integer-minimum width
fill0spacezero-pad between sign and digits; requires align=right (the default)
alignleft, rightrightwhich side gets the pad
base2, 8, 10, 1610digit base; hex uses lowercase
signnegative, always, spacenegativesign for non-negative values
grouppositive integer-digit-group size, reading right-to-left
sepone of _, ,, ., -, :-group separator; required with group= and vice versa
nullsee above-substitute when value is null
jennifer
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

KeyValuesDefaultEffect
precnon-negative integershortestfraction digits (or mantissa fraction digits when sci=true)
trimtrue, falsefalsestrip trailing fraction zeros and the . if all zero
scitrue, falsefalseforce scientific notation (1.23e+03)
padnon-negative integer-minimum width
fill0spacezero-pad between sign and digits; requires align=right (the default)
alignleft, rightrightwhich side gets the pad
signnegative, always, spacenegativesign for non-negative values
grouppositive integer-digit-group size of the integer part, reading right-to-left
sepone of _, ,, ., -, :-group separator; required with group= and vice versa
nullsee 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.

jennifer
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

KeyValuesDefaultEffect
caselower, upper, titlelowertrue/false, TRUE/FALSE, True/False
nullsee 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.

KeyValuesDefaultEffect
sepquoted string", "element separator (between list items, between map entries)
kvquoted string": "key/value separator for map entries
openquoted string[ (list) / { (map)opening bracket
closequoted string] (list) / } (map)closing bracket
depthnon-negative integerunlimitedmax recursion depth; deeper levels collapse to [...] / {...} (depth=0 collapses at the top)
nullskip-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:

KeyApplies toSame as on
precfloat elements%f
trimfloat elements%f
scifloat elements%f
baseint elements%d
signint and float elements%d / %f
modestring elements, map keys included%s
casebool 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 \\ \":

jennifer
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).

jennifer
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.

jennifer
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.

jennifer
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.

jennifer
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

jennifer
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:

text
io.readLine: stdin is owned by the REPL editor

To 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

KindRaised 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.