Read a configuration file: Difference between revisions
Content added Content deleted
Line 1,292: | Line 1,292: | ||
=={{header|D}}== |
=={{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; |
<syntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.regex, std.getopt; |
||
enum VarName(alias var) = var.stringof |
enum VarName(alias var) = var.stringof; |
||
void setOpt(alias Var)(in string line) { |
void setOpt(alias Var)(in string line) { |
||
auto m = match(line, regex(`^` ~ VarName!Var ~ `(\s+(.*))?`)); |
auto m = match(line, regex(`^(?i)` ~ VarName!Var ~ `(?-i)(\s*=?\s+(.*))?`)); |
||
if (!m.empty) { |
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)) |
static if (is(typeof(Var) == string)) |
||
Var = m.captures.length > 2 ? m.captures[2] : ""; |
Var = m.captures.length > 2 ? m.captures[2] : ""; |
||
Line 1,312: | Line 1,313: | ||
void main(in string[] args) { |
void main(in string[] args) { |
||
string fullName, favouriteFruit |
string fullName, favouriteFruit; |
||
string[] otherFamily; |
|||
bool needsPeeling, seedsRemoved; // Default false. |
bool needsPeeling, seedsRemoved; // Default false. |
||
auto f = "readcfg. |
auto f = "readcfg.conf".File; |
||
foreach (line; f.byLine) { |
foreach (line; f.byLine) { |
||
auto opt = line.strip.idup; |
auto opt = line.strip.idup; |
||
setOpt!fullName(opt); |
setOpt!fullName(opt); |
||
setOpt!favouriteFruit(opt); |
setOpt!favouriteFruit(opt); |
||
Line 1,325: | Line 1,329: | ||
} |
} |
||
writefln("% |
writefln("%s = %s", VarName!fullName, fullName); |
||
writefln("% |
writefln("%s = %s", VarName!favouriteFruit, favouriteFruit); |
||
writefln("% |
writefln("%s = %s", VarName!needsPeeling, needsPeeling); |
||
writefln("% |
writefln("%s = %s", VarName!seedsRemoved, seedsRemoved); |
||
writefln("% |
writefln("%s = %s", VarName!otherFamily, otherFamily); |
||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre>fullName = Foo Barber |
||
favouriteFruit = banana |
|||
needsPeeling = true |
|||
seedsRemoved = false |
|||
otherFamily = ["Rhu Barber", "Harry Barber", "John"]</pre> |
|||
=== Variant 2 === |
=== Variant 2 === |