Jump to content

Read a configuration file: Difference between revisions

Line 1,292:
 
=={{header|D}}==
 
{{Incorrect|D|Optional '=' between parameter name and value is not handled.}}
 
<syntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.regex, std.getopt;
 
enum VarName(alias var) = var.stringof.toUpper;
 
void setOpt(alias Var)(in string line) {
auto m = match(line, regex(`^(?i)` ~ VarName!Var ~ `(?-i)(\s*=?\s+(.*))?`));
 
if (!m.empty) {
static if (is(typeof(Var) == string[]))
Var = m.captures.length > 2 ? m.captures[2].split(regex(`\s*,\s*`)) : [""];
static if (is(typeof(Var) == string))
Var = m.captures.length > 2 ? m.captures[2] : "";
Line 1,312 ⟶ 1,313:
 
void main(in string[] args) {
string fullName, favouriteFruit, otherFamily;
string[] otherFamily;
bool needsPeeling, seedsRemoved; // Default false.
 
auto f = "readcfg.txtconf".File;
 
foreach (line; f.byLine) {
auto opt = line.strip.idup;
 
setOpt!fullName(opt);
setOpt!favouriteFruit(opt);
Line 1,325 ⟶ 1,329:
}
 
writefln("%14ss = %s", VarName!fullName, fullName);
writefln("%14ss = %s", VarName!favouriteFruit, favouriteFruit);
writefln("%14ss = %s", VarName!needsPeeling, needsPeeling);
writefln("%14ss = %s", VarName!seedsRemoved, seedsRemoved);
writefln("%14ss = %s", VarName!otherFamily, otherFamily);
}</syntaxhighlight>
{{out}}
<pre> FULLNAMEfullName = Foo Barber
AVOURITEFRUITfavouriteFruit = banana
NEEDSPEELINGneedsPeeling = true
SEEDSREMOVEDseedsRemoved = false
OTHERFAMILYotherFamily = ["Rhu Barber", "Harry Barber", "John"]</pre>
 
=== Variant 2 ===
121

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.