Julia Project: Config Interpreter
A config interpreter is a program that reads settings from a text file and turns them into actions. This lesson parses settings lines and interprets them.
Parse settings into a Dict
The config file is written first in the same block. Its keys print in sorted order.
write("config.txt", "title = Julia\ncount = 3\nstep = 2\n")
lines = readlines("config.txt")
function parse_config(lines)
d = Dict{String,String}()
for line in lines
parts = split(line, " = ")
d[String(parts[1])] = String(parts[2])
end
return d
end
cfg = parse_config(lines)
println(join(sort(collect(keys(cfg))), ", "))Look up a setting and use it
The title prints as stored text. The count and step are parsed as numbers before they are multiplied.
write("config.txt", "title = Julia\ncount = 3\nstep = 2\n")
lines = readlines("config.txt")
function parse_config(lines)
d = Dict{String,String}()
for line in lines
parts = split(line, " = ")
d[String(parts[1])] = String(parts[2])
end
return d
end
cfg = parse_config(lines)
println(cfg["title"])
println(parse(Int, cfg["count"]) * parse(Int, cfg["step"]))Interpret a mode setting
The mode setting says double, so the value is doubled. A different mode would leave the value unchanged.
write("config.txt", "mode = double\nvalue = 4\n")
lines = readlines("config.txt")
function parse_config(lines)
d = Dict{String,String}()
for line in lines
parts = split(line, " = ")
d[String(parts[1])] = String(parts[2])
end
return d
end
cfg = parse_config(lines)
result = cfg["mode"] == "double" ? 2 * parse(Int, cfg["value"]) : parse(Int, cfg["value"])
println(result)Example
write("config.txt", "greeting = hello\ncount = 3\nstep = 2\n")
lines = readlines("config.txt")
function parse_config(lines)
d = Dict{String,String}()
for line in lines
parts = split(line, " = ")
d[String(parts[1])] = String(parts[2])
end
return d
end
cfg = parse_config(lines)
for key in sort(collect(keys(cfg)))
println(key, ": ", cfg[key])
end
println(parse(Int, cfg["count"]) * parse(Int, cfg["step"]))Key points
- Config: a config file is a plain text file that stores settings as lines of names and values.
- Parsing: parsing a config line splits it at the equals sign into a name and a value.
- Lookup: a Dict holds each setting under its name, so a setting can be found by name.
- Sorted order: sorted keys print settings in the same order on every run.
- Interpretation: interpretation turns a stored setting into an action, such as a calculation.
In this example, the config file is written first, then parsed into a Dict. The loop prints every setting in sorted key order, and the last line interprets the count and step settings as a multiplication.
Note
values read from a file are text, so a number setting must be parsed before arithmetic.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
A config file has count = 3 and step = 2. What is count times step?