Programs and the world / Files, input and output
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
Kiln04
03 Programs and the world / 01
Files, input and output
Reading and writing files, arguments, input and the environment, printing, errors and exit statuses.
A program does its work through what's around it: files on the disk, the arguments and input it's given, and what it prints. This page covers those, and then what happens when a program goes wrong: how errors are reported, and the exit status that tells whatever ran the program how it went.
Reading and writing files
The built-in classes File and Folder reach the disk, through static methods. A file is read or written in one go, so there's nothing to open or close. Paths are Strings, relative to the folder hem runs in.
File.read always says what it reads the file as: as: String for text, as: Bytes for any file. There's no default to remember.
try Folder.create("notes")
try File.write("notes/today.txt", content: "Buy milk\n")
try File.append("notes/today.txt", content: "Call Ada\n")
const text = try File.read("notes/today.txt", as: String)
print(text.split("\n")[1]) # prints Call Ada
print(try Folder.list("notes")) # prints ["today.txt"]
try File.delete("notes/today.txt")
print(File.exists("notes/today.txt")) # prints false| Call | Gives | |
|---|---|---|
File.read(path, as: String) | String! | the whole file; it must be UTF-8 text |
File.read(path, as: Bytes) | Bytes! | the whole file, as it is (see Bytes, below) |
File.write(path, content: c) | ! | creates the file, or replaces what's in it; c is a String or Bytes |
File.append(path, content: c) | ! | adds to the end, creating the file if needed |
File.copy(path, to: other) | ! | the file in a second place, replacing what's there |
File.move(path, to: other) | ! | the file in its new place only |
File.delete(path) | ! | |
File.exists(path) | Boolean | true only for a file, not a folder |
Folder.list(path) | [String]! | the names inside, sorted |
Folder.create(path) | ! | creates missing parent folders too; fine if it exists |
Folder.exists(path) | Boolean |
Everything that touches the disk can fail, except the exists checks, so each call is handled with try or rescue. Every failure has a kind, so a program can tell a file that isn't there from one it isn't allowed to read. This one treats a missing file as an empty one:
const notes = File.read("missing.txt", as: String) rescue error
if error.kind == ErrorKind.missing
return ""
end
print(error.message)
return ""
end
print(notes.length) # prints 0File.move renames the file where it can, and copies it, then deletes it, from one disk to another. A copy or a move to a folder that isn't there fails with kind missing.
Bytes
Bytes are a file as it is on the disk, text or not: an image, a PDF, a zip. Each byte is an Int from 0 to 255. File.read(path, as: Bytes) reads any file, and File.write writes Bytes as they are:
const photo = Bytes([255, 216, 255, 224])
try File.write("photo.jpg", content: photo)
const read = try File.read("photo.jpg", as: Bytes)
print(read) # prints <4 bytes>
print(read[0]) # prints 255
print(read.contains(Bytes([255, 216]), at: Placement.start)) # prints true
print(read == photo) # prints true
try File.copy("photo.jpg", to: "kept.jpg")
try File.delete("photo.jpg")
print(File.exists("kept.jpg")) # prints true
try File.delete("kept.jpg")- Bytes are made of text,
Bytes("héllo"), its UTF-8; or of Ints,Bytes([255, 216]). Ints written out are held to 0 to 255 before the program runs; any others when the Bytes are made, soBytes(numbers)is aBytes!that fails with kindinvalid. bytes.text()is the text they hold, aString!: it fails with kindnot_textwhen they aren't UTF-8.bytes[i]is one byte, an Int.length,slice,contains,+and==work as they do for text (see built-in methods), counting bytes.- Bytes don't change: make new ones, like
bytes.slice(from: 0, to: 2) + Bytes([7]). printshows how many there are,<4 bytes>, not what they are. Bytes can't become JSON or a form's field: keep them in a file of their own.
const hello = Bytes("héllo")
print(hello.length) # prints 6
print(try hello.text()) # prints héllo
print(Bytes([1, 300])) # error: 300 isn't a byte: a byte is an Int from 0 to 255Input, arguments and the environment
The built-in classes Program and Input give a program what it was started with, and what's typed or piped into it:
| Use | Gives | |
|---|---|---|
Program.arguments | [String] | what followed the file in hem run app.hem a b |
Program.env(name) | String? | an environment variable, or nil if it isn't set |
Program.exit(code) | stops the program, with that exit code (0 to 255), after writing out what it printed | |
Program.components() | {String: Bytes}! | the files a page needs for the program's components, by name (see components) |
Input.line() | String? | the next line of input, without its line break; nil at the end |
Input.line(prompt) | String? | the same, after showing prompt on the line the answer is typed on |
Program.arguments is a value, like a static; Program.env(name) and Input.line() are calls. Both Program.env and Input.line can give nil, which code checks for:
const arguments = Program.arguments
print(arguments.length) # prints 0
const home = Program.env("HEM_GUIDE_NOT_SET")
print(home == nil) # prints trueInput.line() gives nil at the end of the input, so a program that reads every line it's given loops until then. This one counts them:
var count = 0
var line = Input.line()
while line != nil
count = count + 1
line = Input.line()
end
print(count) # prints 0To ask a question, give Input.line a prompt, and the answer is typed on the same line: const name = Input.line("Name: "). Everything printed before is shown first.
Stopping the program
Program.exit stops the whole program, wherever it's called. Use it at the end of a script that failed, so whatever ran it knows: 0 means it worked, anything else that it didn't (see exit statuses).
File.write("report.txt", content: report) rescue error
print("Can't write the report: #{error.message}")
Program.exit(1)
endPrinting
print(value) prints one value followed by a line break, and returns nil.
print(42) # prints 42
print(1 + 2) # prints 3
print(-5) # prints -5Each kind of value prints its own way:
| Value | Prints |
|---|---|
| Int | 42, -7 |
| Float | Always with a . or an exponent: 3.0, 0.5, 1e20, 1e-6 |
| String | Its text, without quotes |
| Array | [1, 2, 3]; strings inside are quoted: ["a", "b"] |
| Hash | {"Ada": 36, "Grace": 85}, in the order keys were added |
| Object | Account(owner: "Ada", balance: 50.0): only readable and writable fields |
| Float overflow | Infinity, -Infinity, NaN |
| nil | nil |
print takes exactly one argument. To print several values, use several lines:
const width = 3
const height = 4
print(width) # prints 3
print(height) # prints 4Errors
When something's wrong, Hematite says where. Every error reports the file, line and column:
app.hem:2:5: error: unexpected character '$'Lines and columns start at 1, and columns count characters, not bytes. An error comes at one of two times:
- Found before running: exit 65
- Syntax errors, name errors such as undeclared variables or changing a
const, and type errors such as"a" + 1or using a value that might benil. If any line has one, no line runs. - At runtime: exit 70
- The program stops at the failing line. Output from earlier lines has already been printed. A failure that a
tryin the script passes on stops the program the same way.
One mistake, one error
Every error found before running is reported, in order (up to 50), so they can all be fixed in one go. And one mistake gives one error, so the list isn't padded with errors that follow from another:
- A line with a syntax error reports only that one. When a line ends with an operator or leaves a bracket open, it goes on into the next line; the error points at that operator or bracket.
- A variable, method, class or field whose declaration has a mistake still exists, so using it isn't a mistake too: what uses it is checked once the mistake is fixed.
- A type that names nothing (
[Strng]) is reported where it's written; values of it aren't checked until then.
Exit statuses
When a program ends, its exit status tells whatever ran it, like a shell or another script, how it went. Besides the code a program gives Program.exit, these are the statuses hem uses:
| Status | Meaning |
|---|---|
| 0 | Success |
| 64 | Wrong command-line usage |
| 65 | Error found before running (syntax, names or types); nothing ran |
| 66 | The program's own file could not be read: missing, a directory, or not UTF-8. (An import that isn't there is found before running, so it's 65.) |
| 70 | Runtime error; the program stopped early |