Read a configuration file: Difference between revisions

m
m (→‎{{header|Raku}}: .perl -> .raku)
m (→‎{{header|Wren}}: Minor tidy)
 
(22 intermediate revisions by 18 users not shown)
Line 53:
* [[Update a configuration file]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F readconf(fname)
[String = String] ret
L(=line) File(fname).read_lines()
line = line.trim((‘ ’, "\t", "\r", "\n"))
I line == ‘’ | line.starts_with(‘#’)
L.continue
 
V boolval = 1B
I line.starts_with(‘;’)
line = line.ltrim(‘;’)
 
I line.split_py().len != 1
L.continue
boolval = 0B
 
V bits = line.split(‘ ’, 2, group_delimiters' 1B)
String k, v
I bits.len == 1
k = bits[0]
v = String(boolval)
E
(k, v) = bits
ret[k.lowercase()] = v
R ret
 
V conf = readconf(‘config.txt’)
L(k, v) sorted(conf.items())
print(k‘ = ’v)</syntaxhighlight>
 
{{out}}
<pre>
favouritefruit = banana
fullname = Foo Barber
needspeeling = 1B
otherfamily = Rhu Barber, Harry Barber
seedsremoved = 0B
</pre>
 
=={{header|Ada}}==
Line 59 ⟶ 100:
Uses package Config available at SourceForge:
https://sourceforge.net/projects/ini-files/
<langsyntaxhighlight Adalang="ada">with Config; use Config;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 75 ⟶ 116:
Put_Line("seedsremoved = " & Boolean'Image(seedsremoved));
Put_Line("otherfamily = " & otherfamily);
end;</langsyntaxhighlight>
 
{{out}}
Line 86 ⟶ 127:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">record r, s;
integer c;
file f;
Line 143 ⟶ 184:
l.ucall(o_, 0, ", ");
o_("\n");
}</langsyntaxhighlight>
{{Out}}
<pre>FAVOURITEFRUIT: banana
Line 150 ⟶ 191:
SEEDSREMOVED: false
OTHERFAMILY: Rhu Barber, Harry Barber,</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">parseConfig: function [f][
lines: split.lines read f
lines: select map lines 'line [strip replace line {/[#;].*/} ""]
'line [not? empty? line]
result: #[]
 
fields: loop lines 'line [
field: first match line {/^[A-Z]+/}
rest: strip replace line field ""
parts: select map split.by:"," rest => strip 'part -> not? empty? part
 
val: null
case [(size parts)]
when? [= 0] -> val: true
when? [= 1] -> val: first parts
else -> val: parts
 
result\[lower field]: val
]
 
return result
]
 
loop parseConfig relative "config.file" [k,v][
if? block? v -> print [k "->" join.with:", " v]
else -> print [k "->" v]
]</syntaxhighlight>
 
{{out}}
 
<pre>fullname -> Foo Barber
favouritefruit -> banana
needspeeling -> true
otherfamily -> Rhu Barber, Harry Barber</pre>
 
=={{header|AutoHotkey}}==
 
<syntaxhighlight lang="autohotkey">
<lang AutoHotkey>
; Author: AlephX, Aug 18 2011
data = %A_scriptdir%\rosettaconfig.txt
Line 191 ⟶ 269:
}
msgbox, FULLNAME %fullname%`nFAVOURITEFRUIT %FAVOURITEFRUIT%`nNEEDSPEELING %NEEDSPEELING%`nSEEDSREMOVED %SEEDSREMOVED%`nOTHERFAMILY %OTHERFAMILY1% + %OTHERFAMILY2%
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f READ_A_CONFIGURATION_FILE.AWK
BEGIN {
Line 228 ⟶ 306:
return(str)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 246 ⟶ 324:
 
This is a fully functional program with generic reading of a configuration file with variable names up to 20 characters and values up to 30 characters. Both limits can be expanded as needed but remember how quick it can eat RAM. It can read configuration files with variables separated of values through spaces or equal sign (=), so it will find "Variable = Value" or "Variable Value". Values can be separated by commas in configuration file and it will create a virtual array. This program will omit lines begining with #, ; or null.
<langsyntaxhighlight lang="qbasic">
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' Read a Configuration File V1.0 '
Line 500 ⟶ 578:
 
END FUNCTION
</syntaxhighlight>
</lang>
Run
<pre>
Line 526 ⟶ 604:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> BOOL = 1
NAME = 2
ARRAY = 3
Line 586 ⟶ 664:
WHEN ARRAY: = !^array$()
ENDCASE
= 0</langsyntaxhighlight>
{{out}}
<pre>
Line 602 ⟶ 680:
'''optimized'''
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 772 ⟶ 850:
return 0;
 
}</langsyntaxhighlight>
 
{{out}}
Line 788 ⟶ 866:
'''unoptimized'''
 
<langsyntaxhighlight lang="cpp">#include "stdafx.h"
#include <iostream>
#include <fstream>
Line 893 ⟶ 971:
return 0;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 903 ⟶ 981:
 
'''Solution without Boost libraries. No optimisation.'''
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <iomanip>
#include <string>
Line 978 ⟶ 1,056:
read_config(inp,outp);
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 988 ⟶ 1,066:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns read-conf-file.core
(:require [clojure.java.io :as io]
[clojure.string :as str])
Line 1,035 ⟶ 1,113:
(defn -main
[filename]
(output conf-keys (mk-conf (get-lines filename))))</langsyntaxhighlight>
 
{{out}}
Line 1,047 ⟶ 1,125:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol">
identification division.
program-id. ReadConfiguration.
Line 1,144 ⟶ 1,222:
end-perform
.
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,158 ⟶ 1,236:
=={{header|Common Lisp}}==
Using parser-combinators available in quicklisp:
<langsyntaxhighlight lang="lisp">(ql:quickload :parser-combinators)
 
(defpackage :read-config
Line 1,197 ⟶ 1,275:
((eq parsed nil) (error "config parser error: ~a" line))
(t (setf (gethash (car parsed) hash) (cdr parsed))))))
hash))</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="lisp">READ-CONFIG> (with-open-file (s "test.cfg") (parse-config s))
#<HASH-TABLE :TEST EQUAL :COUNT 4 {100BD25B43}>
READ-CONFIG> (maphash (lambda (k v) (print (list k v))) *)
Line 1,211 ⟶ 1,289:
NIL
NIL
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<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.toUpper;
 
enum VarName(alias var) = var.stringof;
 
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,231 ⟶ 1,313:
 
void main(in string[] args) {
string fullName, favouriteFruit, otherFamily;
string[] otherFamily;
bool needsPeeling, seedsRemoved; // Default false.
 
auto f = "readcfg.txt".File;
auto f = "readcfg.conf".File;
 
foreach (line; f.byLine) {
auto opt = line.strip.idup;
 
setOpt!fullName(opt);
setOpt!favouriteFruit(opt);
Line 1,244 ⟶ 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);
}</langsyntaxhighlight>
{{out}}
<pre> FULLNAMEfullName = Foo Barber
AVOURITEFRUITfavouriteFruit = banana
NEEDSPEELINGneedsPeeling = true
SEEDSREMOVEDseedsRemoved = false
OTHERFAMILYotherFamily = ["Rhu Barber", "Harry Barber", "John"]</pre>
 
=== Variant 2 ===
Correct version with handling optional '=' sign. Config is assembled into one class.
 
<syntaxhighlight lang="d">
import std.stdio, std.string, std.conv, std.regex, std.algorithm;
 
auto reNameValue = ctRegex!(`^(\w+)\s*=?\s*(\S.*)?`);// ctRegex creates regexp parser at compile time
 
// print Config members w/o hardcoding names
void PrintMembers(Config c)
{
foreach(M; __traits(derivedMembers, Config))
writeln(M ~ ` = `, __traits(getMember, c, M));
}
 
void main(in string[] args /* arg[0] is EXE name */) {
 
auto cfg = new Config;
auto f = args[1].File;// open config given in command line
foreach (line; f.byLineCopy.map!(s => s.strip).filter!(s => !s.empty && s[0] != '#' && s[0] != ';')) {// free loop from unnecessary lines
auto m = matchFirst(line, reNameValue);
if (m.empty) { writeln(`Wrong config line: ` ~ line); continue; }
 
switch(m[1].toUpper) {
case `FULLNAME`: cfg.FullName = m[2]; break;
case `FAVOURITEFRUIT`: cfg.FavouriteFruit = m[2]; break;
case `NEEDSPEELING`: cfg.needsPeeling = (m[2].toUpper != `FALSE`); break;
case `SEEDSREMOVED`: cfg.seedsRemoved = (m[2].toUpper != `FALSE`); break;
case `OTHERFAMILY`: cfg.otherFamily = split(m[2], regex(`\s*,\s*`)); break;// regex allows to avoid 'strip' step
default:
writeln(`Unknown config variable: ` ~ m[1]);
}
}
PrintMembers(cfg);
}
 
class Config
{
string FullName;
string FavouriteFruit;
bool needsPeeling;
bool seedsRemoved;
string[] otherFamily;
}
</syntaxhighlight>
{{out}}
On config:
<pre>
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
 
# This is the fullname parameter
FULLNAME Foo Barber
 
# This is a favourite fruit
FAVOURITEFRUIT = banana
 
# This is a boolean that should be set
NeeDSPeeLING
 
# This boolean is commented out
; SEEDSREMOVED
 
# Configuration option names are not case sensitive, but configuration parameter
# data is case sensitive and may be preserved by the application program.
 
# An optional equals sign can be used to separate configuration parameter data
# from the option name. This is dropped by the parser.
 
# A configuration option may take multiple parameters separated by commas.
# Leading and trailing whitespace around parameter names and parameter data fields
# are ignored by the application program.
 
OTHERFAMILY Rhu Barber , Harry Barber, John
</pre>
Output is:
<pre>
FullName = Foo Barber
FavouriteFruit = banana
needsPeeling = true
seedsRemoved = false
otherFamily = ["Rhu Barber", "Harry Barber", "John"]
</pre>
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ open input config.ini
$ loop:
$ read /end_of_file = done input line
Line 1,275 ⟶ 1,446:
$ goto loop
$ done:
$ close input</langsyntaxhighlight>
{{out}}
<pre>$ @read_a_configuration_file
Line 1,281 ⟶ 1,452:
FAVOURITEFRUIT = "banana"
NEEDSPEELING = "true"</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| uSettings}}
Unit for manager config files, used in [[Update a configuration file]].
<syntaxhighlight lang="delphi">
unit uSettings;
 
interface
 
uses
System.SysUtils, System.IoUtils, System.Generics.Collections, System.Variants;
 
type
TVariable = record
value: variant;
function ToString: string;
class operator Implicit(a: variant): TVariable;
class operator Implicit(a: TVariable): TArray<string>;
class operator Implicit(a: TVariable): string;
end;
 
TSettings = class(TDictionary<string, TVariable>)
private
function GetVariable(key: string): TVariable;
procedure SetVariable(key: string; const Value: TVariable);
function GetKey(line: string; var key: string; var value: variant; var
disable: boolean): boolean;
function GetAllKeys: TList<string>;
public
procedure LoadFromFile(Filename: TfileName);
procedure SaveToFile(Filename: TfileName);
property Variable[key: string]: TVariable read GetVariable write SetVariable; default;
end;
 
implementation
 
{ TVariable }
 
class operator TVariable.Implicit(a: variant): TVariable;
begin
Result.value := a;
end;
 
class operator TVariable.Implicit(a: TVariable): TArray<string>;
begin
if VarIsType(a.value, varArray or varOleStr) then
Result := a.value
else
raise Exception.Create('Error: can''t convert this type data in array');
end;
 
class operator TVariable.Implicit(a: TVariable): string;
begin
Result := a.ToString;
end;
 
function TVariable.ToString: string;
var
arr: TArray<string>;
begin
if VarIsType(value, varArray or varOleStr) then
begin
arr := value;
Result := string.Join(', ', arr).Trim;
end
else
Result := value;
Result := Result.Trim;
end;
 
{ TSettings }
 
function TSettings.GetAllKeys: TList<string>;
var
key: string;
begin
Result := TList<string>.Create;
for key in Keys do
Result.Add(key);
end;
 
function TSettings.GetKey(line: string; var key: string; var value: variant; var
disable: boolean): boolean;
var
line_: string;
j: integer;
begin
line_ := line.Trim;
Result := not (line_.IsEmpty or (line_[1] = '#'));
if not Result then
exit;
 
disable := (line_[1] = ';');
if disable then
delete(line_, 1, 1);
 
var data := line_.Split([' '], TStringSplitOptions.ExcludeEmpty);
case length(data) of
1: //Boolean
begin
key := data[0].ToUpper;
value := True;
end;
 
2: //Single String
begin
key := data[0].ToUpper;
value := data[1].Trim;
end;
 
else // Mult String value or Array of value
begin
key := data[0];
delete(line_, 1, key.Length);
if line_.IndexOf(',') > -1 then
begin
data := line_.Trim.Split([','], TStringSplitOptions.ExcludeEmpty);
for j := 0 to High(data) do
data[j] := data[j].Trim;
value := data;
end
else
value := line_.Trim;
end;
end;
Result := true;
end;
 
function TSettings.GetVariable(key: string): TVariable;
begin
key := key.Trim.ToUpper;
if not ContainsKey(key) then
add(key, false);
 
result := Items[key];
end;
 
procedure TSettings.LoadFromFile(Filename: TfileName);
var
key, line: string;
value: variant;
disabled: boolean;
Lines: TArray<string>;
begin
if not FileExists(Filename) then
exit;
 
Clear;
Lines := TFile.ReadAllLines(Filename);
for line in Lines do
begin
if GetKey(line, key, value, disabled) then
begin
if disabled then
AddOrSetValue(key, False)
else
AddOrSetValue(key, value)
end;
end;
end;
 
procedure TSettings.SaveToFile(Filename: TfileName);
var
key, line: string;
value: variant;
disabled: boolean;
Lines: TArray<string>;
i: Integer;
All_kyes: TList<string>;
begin
All_kyes := GetAllKeys();
SetLength(Lines, 0);
i := 0;
if FileExists(Filename) then
begin
Lines := TFile.ReadAllLines(Filename);
for i := high(Lines) downto 0 do
begin
if GetKey(Lines[i], key, value, disabled) then
begin
if not ContainsKey(key) then
begin
Lines[i] := '; ' + Lines[i];
Continue;
end;
 
All_kyes.Remove(key);
 
disabled := VarIsType(Variable[key].value, varBoolean) and (Variable[key].value
= false);
if not disabled then
begin
if VarIsType(Variable[key].value, varBoolean) then
Lines[i] := key
else
Lines[i] := format('%s %s', [key, Variable[key].ToString])
end
else
Lines[i] := '; ' + key;
end;
end;
 
end;
 
// new keys
i := high(Lines) + 1;
SetLength(Lines, Length(Lines) + All_kyes.Count);
for key in All_kyes do
begin
Lines[i] := format('%s %s', [key, Variable[key].ToString]);
inc(i);
end;
 
Tfile.WriteAllLines(Filename, Lines);
 
All_kyes.Free;
end;
 
procedure TSettings.SetVariable(key: string; const Value: TVariable);
begin
AddOrSetValue(key.Trim.ToUpper, Value);
end;
end.
</syntaxhighlight>
Usage of unit:
<syntaxhighlight lang="delphi">
program ReadAConfigFile;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
uSettings;
 
const
FileName = 'Config.txt';
 
var
Settings: TSettings;
 
procedure show(key: string; value: string);
begin
writeln(format('%14s = %s', [key, value]));
end;
 
begin
Settings := TSettings.Create;
Settings.LoadFromFile(FileName);
 
for var k in Settings.Keys do
show(k, Settings[k]);
 
Settings.Free;
Readln;
end.</syntaxhighlight>
{{out}}
<pre>FAVOURITEFRUIT = banana
FULLNAME = Foo Barber
NEEDSPEELING = True
SEEDSREMOVED = False
OTHERFAMILY = Rhu Barber, Harry Barber</pre>
 
=={{header|EchoLisp}}==
{{Incorrect|EchoLisp|Makes no attempt to parse the configuration file of the task description.}}
There is no 'config file' in EchoLisp, but a '''(preferences)''' function which is automatically loaded and evaluated at boot-time, and automatically saved after modification. This function can set global parameters, or call other functions, or load libraries.
<langsyntaxhighlight lang="lisp">
(edit 'preferences)
;; current contents to edit is displayed in the input box
Line 1,301 ⟶ 1,733:
; SEEDSREMOVED
(define OTHERFAMILY '("Rhu Barber" "Harry Barber")))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="lisp">
;; press F5 or COMMAND-R to reload
EchoLisp - 2.13.12
Line 1,313 ⟶ 1,745:
SEEDSREMOVED
😡 error: #|user| : unbound variable : SEEDSREMOVED
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Configuration_file do
def read(file) do
File.read!(file)
Line 1,351 ⟶ 1,783:
end
 
Configuration_file.task</langsyntaxhighlight>
 
{{out}}
Line 1,365 ⟶ 1,797:
=={{header|Erlang}}==
 
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( configuration_file ).
 
Line 1,387 ⟶ 1,819:
option_from_binaries_value( [Value] ) -> erlang:binary_to_list(Value);
option_from_binaries_value( Values ) -> [erlang:binary_to_list(X) || X <- Values].
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,401 ⟶ 1,833:
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,462 ⟶ 1,894:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
Line 1,472 ⟶ 1,904:
 
Something worth noting is that the FORTH interpreter will halt on a syntax error in the config.txt file. If this was not the proscribed behavior for the application then the FORTH error handler would need modification. This is possible in most systems by using the system error words (abort, catch, throw) appropriately while interpreting the config file.
<syntaxhighlight lang="text">\ declare the configuration variables in the FORTH app
FORTH DEFINITIONS
 
Line 1,496 ⟶ 1,928:
: # ( -- ) 1 PARSE 2DROP ; \ parse line and throw away
: = ( addr --) 1 PARSE trim ROT PLACE ; \ string assignment operator
synonym' ;# alias ; # \ 2nd comment operator is simple
 
FORTH DEFINITIONS
Line 1,513 ⟶ 1,945:
CR ." Family:"
CR otherfamily(1) $.
CR otherfamily(2) $. ;</langsyntaxhighlight>
The config file would look like this
<pre>
Line 1,539 ⟶ 1,971:
Rhu Barber
Harry Barber ok</PRE>
 
Note that parsing a config file using the forth text interpreter this way is probably only safe if you are the only one that edits the config file, as it can execute any forth word.
 
=={{header|Fortran}}==
 
<syntaxhighlight lang="fortran">
<lang Fortran>
program readconfig
implicit none
Line 1,651 ⟶ 2,085:
 
end program
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub split (s As Const String, sepList As Const String, result() As String)
Line 1,749 ⟶ 2,183:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,759 ⟶ 2,193:
Other family(0) = Rhu Barber
Other family(1) = Harry Barber
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn SaveConfiguration
CFDictionaryRef defaults = @{¬
@"FULLNAME" : @"Foo Barber",¬
@"FAVOURITEFRUIT" : @"banana",¬
@"NEEDSPEELING" : @YES,¬
@"SEEDSREMOVED" : @NO,¬
@"OTHERFAMILY" : @[@"Rhu Barber", @"Harry Barber"]}
UserDefaultsRegisterDefaults( defaults )
end fn
 
local fn ReadConfiguration
CFStringRef tempStr
CFStringRef fullname = fn UserDefaultsString( @"FULLNAME" )
CFStringRef favouritefruit = fn UserDefaultsString( @"FAVOURITEFRUIT" )
BOOL needspeeling = fn UserDefaultsBool( @"NEEDSPEELING" )
BOOL seedsremoved = fn UserDefaultsBool( @"SEEDSREMOVED" )
CFArrayRef otherfamily = fn UserDefaultsArray( @"OTHERFAMILY" )
printf @"Saved configuration:\n"
printf @"FULLNAME: %@", fullname
printf @"FAVOURITEFRUIT: %@", favouritefruit
if needspeeling == YES then tempStr = @"TRUE" else tempStr = @"FALSE"
printf @"NEEDSPEELING: %@", tempStr
if seedsremoved == YES then tempStr = @"TRUE" else tempStr = @"FALSE"
printf @"SEEDSREMOVED: %@", @"(undefined)"
printf @"OTHERFAMILY: %@, %@", otherfamily[0], otherfamily[1]
end fn
 
fn SaveConfiguration
fn ReadConfiguration
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Saved configuration:
 
FULLNAME: Foo Barber
FAVOURITEFRUIT: banana
NEEDSPEELING: TRUE
SEEDSREMOVED: (undefined)
OTHERFAMILY: Rhu Barber, Harry Barber
</pre>
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">Public Sub Form_Open()
Dim fullname As String = Settings["fullname", "Foo Barber"] 'If fullname is empty then use the default "Foo Barber"
Dim favouritefruit As String = Settings["favouritefruit", "banana"]
Line 1,777 ⟶ 2,259:
Print fullname
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,786 ⟶ 2,268:
=={{header|Go}}==
This make assumptions about the way the config file is supposed to be structured similar to the ones made by the Python solution.
<langsyntaxhighlight lang="go">package config
 
import (
Line 1,945 ⟶ 2,427:
 
return v, nil
}</langsyntaxhighlight>
 
Usage example:
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,010 ⟶ 2,492:
fmt.Printf("SEEDSREMOVED: %q\n", seedsremoved)
fmt.Printf("OTHERFAMILY: %q\n", otherfamily)
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def config = [:]
def loadConfig = { File file ->
String regex = /^(;{0,1})\s*(\S+)\s*(.*)$/
Line 2,027 ⟶ 2,509:
}
}
}</langsyntaxhighlight>
Testing:
<langsyntaxhighlight lang="groovy">loadConfig new File('config.ini')
config.each { println it }</langsyntaxhighlight>
{{out}}
<pre>FULLNAME=Foo Barber
Line 2,041 ⟶ 2,523:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">
import Data.Char
import Data.List
Line 2,075 ⟶ 2,557:
defaultConfig :: Config
defaultConfig = Config "" "" False False []
</syntaxhighlight>
</lang>
 
Or, use Data.Configfile:
 
<langsyntaxhighlight lang="haskell">
import Data.ConfigFile
import Data.Either.Utils
Line 2,088 ⟶ 2,570:
let username = getSetting cp "username"
password = getSetting cp "password"
</syntaxhighlight>
</lang>
This works with configuration files in standard format, i.e.,
# this is a comment
Line 2,099 ⟶ 2,581:
If it contains any value then it can considered as being equivalent to <i>true</i>:
 
<langsyntaxhighlight lang="unicon">procedure main(A)
ws := ' \t'
vars := table()
Line 2,128 ⟶ 2,610:
write(s[1:-2])
}
end</langsyntaxhighlight>
 
Sample run on above input:
Line 2,144 ⟶ 2,626:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">require'regex'
set=:4 :'(x)=:y'
 
Line 2,165 ⟶ 2,647:
cfg cfgBoolean 'seedsremoved'
i.0 0
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> taskCfg 'fruit.conf'
(,' = ',]&.do)&>;: 'fullname favouritefruit needspeeling seedsremoved'
fullname = Foo Barber
favouritefruit = banana
needspeeling = 1
seedsremoved = 0 </langsyntaxhighlight>
 
=={{header|Java}}==
A more natural way to do this in Java would be Properties.load(InputStream) but the example data is not in the format expected by that method (equals signs are optional).
<langsyntaxhighlight Javalang="java">import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Line 2,247 ⟶ 2,729:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,254 ⟶ 2,736:
A more functional and concise approach using Java 8:
 
<langsyntaxhighlight Javalang="java">import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Line 2,294 ⟶ 2,776:
return result;
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,302 ⟶ 2,784:
In JavaScript using an object makes more sense than local variables. This function takes our config file in plain text as the parameter.
 
<langsyntaxhighlight lang="javascript">function parseConfig(config) {
// this expression matches a line starting with an all capital word,
// and anything after it
Line 2,327 ⟶ 2,809:
return configObject;
} </langsyntaxhighlight>
 
The result is an object, which can be represented with this JSON.
 
<langsyntaxhighlight lang="javascript">{
"FULLNAME": " Foo Barber",
"FAVOURITEFRUIT": " banana",
Line 2,340 ⟶ 2,822:
]
}
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 2,346 ⟶ 2,828:
 
In the following, in the case of collisions, the last-most specification prevails.
<langsyntaxhighlight lang="jq">def parse:
 
def uc: .name | ascii_upcase;
Line 2,367 ⟶ 2,849:
end);
 
parse</langsyntaxhighlight>
 
'''Invocation'''
Line 2,387 ⟶ 2,869:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function readconf(file)
vars = Dict()
for line in eachline(file)
Line 2,410 ⟶ 2,892:
readconf("test.conf")
 
@show fullname favouritefruit needspeeling otherfamily</langsyntaxhighlight>
 
{{out}}
Line 2,422 ⟶ 2,904:
{{works with|Kotlin|1.0.6}}
This example is more verbose than it has to be because of increased effort in providing immutability to the configuration class.
<langsyntaxhighlight lang="scala">import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
Line 2,458 ⟶ 2,940:
private fun toKeyValuePair(line: String) = line.split(Regex(" "), 2).let {
Pair(it[0], if (it.size == 1) "" else it[1])
}</langsyntaxhighlight>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Read a configuration file
 
# # Variables:
#
 
# # The configuration file (below) could be read in from a file
# But this method keeps everything together.
# e.g. config=$(< /path/to/config_file)
 
integer config_num=0
config='# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# program. Blank lines are also ignored by the application program.
 
# This is the fullname parameter
FULLNAME Foo Barber
 
# This is a favourite fruit
FAVOURITEFRUIT banana
 
# This is a boolean that should be set
NEEDSPEELING
 
# This boolean is commented out
; SEEDSREMOVED
 
# Configuration option names are not case sensitive, but configuration parameter
# data is case sensitive and may be preserved by the application program.
 
# An optional equals sign can be used to separate configuration parameter data
# from the option name. This is dropped by the parser.
 
# A configuration option may take multiple parameters separated by commas.
# Leading and trailing whitespace around parameter names and parameter data fields
# are ignored by the application program.
 
OTHERFAMILY Rhu Barber, Harry Barber'
 
isComment='#|;'
paraDelim=' |='
boolean="SEEDSREMOVED|NEEDSPEELING"
 
typeset -T Config_t=(
typeset -h 'Full name' fullname
typeset -h 'Favorite fruit' favouritefruit
typeset -h 'Boolean NEEDSPEELING' needspeeling=false
typeset -h 'Boolean SEEDSREMOVED' seedsremoved=false
typeset -a -h 'Other family' otherfamily
 
function set_name {
typeset fn ; fn=$(echo $1) # Strip any leading/trailing white space
_.fullname="${fn}"
}
 
function set_fruit {
typeset fruit ; fruit=$(echo $1)
_.favouritefruit="${fruit}"
}
 
function set_bool {
typeset bool ; typeset -u bool=$1
 
case ${bool} in
NEEDSPEELING) _.needspeeling=true ;;
SEEDSREMOVED) _.seedsremoved=true ;;
esac
}
 
function set_family {
typeset ofam ; ofam=$(echo $1)
typeset farr i ; typeset -a farr ; integer i
 
oldIFS="$IFS" ; IFS=',' ; farr=( ${ofam} ) ; IFS="${oldIFS}"
for ((i=0; i<${#farr[*]}; i++)); do
_.otherfamily[i]=$(echo ${farr[i]})
done
}
)
 
# # Functions:
#
 
# # Function _parseconf(config) - Parse uncommented lines
#
function _parseconf {
typeset _cfg ; _cfg="$1"
typeset _conf ; nameref _conf="$2"
 
echo "${_cfg}" | \
while read; do
[[ $REPLY == @(${isComment})* ]] || [[ $REPLY == '' ]] && continue
_parseline "$REPLY" _conf
done
}
 
function _parseline {
typeset _line ; _line=$(echo $1)
typeset _conf ; nameref _conf="$2"
typeset _param _value ; typeset -u _param
 
_param=${_line%%+(${paraDelim})*}
_value=${_line#*+(${paraDelim})}
 
if [[ ${_param} == @(${boolean}) ]]; then
_conf.set_bool ${_param}
else
case ${_param} in
FULLNAME) _conf.set_name "${_value}" ;;
FAVOURITEFRUIT) _conf.set_fruit ${_value} ;;
OTHERFAMILY) _conf.set_family "${_value}" ;;
esac
fi
}
######
# main #
######
 
typeset -a configuration # Indexed array of configurations
Config_t configuration[config_num]
_parseconf "${config}" configuration[config_num]
 
for cnum in ${!configuration[*]}; do
printf "fullname = %s\n" "${configuration[cnum].fullname}"
printf "favouritefruit = %s\n" ${configuration[cnum].favouritefruit}
printf "needspeeling = %s\n" ${configuration[cnum].needspeeling}
printf "seedsremoved = %s\n" ${configuration[cnum].seedsremoved}
for ((i=0; i<${#configuration[cnum].otherfamily[*]}; i++)); do
print "otherfamily($((i+1))) = ${configuration[cnum].otherfamily[i]}"
done
done
</syntaxhighlight>
{{out}}<pre>
fullname = Foo Barber
favouritefruit = banana
needspeeling = true
seedsremoved = false
otherfamily(1) = Rhu Barber
otherfamily(2) = Harry Barber
</pre>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(config = '# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
Line 2,530 ⟶ 3,157:
'<br />'
#otherfamily
'<br />'</langsyntaxhighlight>
{{out}}
<pre>Foo Barber
Line 2,539 ⟶ 3,166:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
dim confKeys$(100)
dim confValues$(100)
Line 2,609 ⟶ 3,236:
next i
end function
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,622 ⟶ 3,249:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">conf = {}
 
fp = io.open( "conf.txt", "r" )
Line 2,661 ⟶ 3,288:
print( "", entry )
end
end</langsyntaxhighlight>
 
=={{header|MathematicaM2000 Interpreter}}==
The congiguration.txt is in a zip file in Encode64 Binary part
<lang Mathematica>
We can export to disk or use it as is, through the buffer
ClearAll[CreateVar, ImportConfig];
 
to make it I use this:
<syntaxhighlight lang="m2000 interpreter">
Declare zip compressor
a$=str$(a$)
Method zip, "AddFromMemory",a$, "configuration.txt" as ok
Method zip,"CreateZipBuffer" as buf1
clipboard String$(eval$(buf1) as Encode64)
 
//where a$ defined (before)
a$={text here from first line
until last line
}
</syntaxhighlight>
 
 
To do Declare Zip Nothing is optional (for User forms isn't though)
 
 
<syntaxhighlight lang="m2000 interpreter">
module check(a$, id as list){
Document Export$
nl$={
}
dim L$() : L$()=piece$(a$,nl$)
if len(L$())=0 then exit
for i=0 to len(L$())-1
a$=trim$(L$(i))
b$=left$(a$, 1)
select case b$
case ";"
examineValue(true)
case >"#"
examineValue(false)
end select
next
Report Export$ // result or Clipboard Export$
Sub examineValue(NotUsed as boolean)
local i
if NotUsed then
a$=trim$(mid$(a$,2))+" "
b$=leftpart$(a$," ")
else
a$+=" "
b$=leftpart$(a$," ")
end if
a$=trim$(rightpart$(a$," "))
// optional = removed
if left$(a$,1)="=" then a$=trim$(mid$(a$,2))
// if not exist ignore it
if exist(id,ucase$(b$)) then
if len(a$)=0 then // we have a boolean
Export$=b$+" = "+if$(NotUsed->"false", "true")+nl$
else.if instr(a$,",")>0 then // multiple value
local a$()
a$()=piece$(a$,",")
for i=0 to len(a$())-1
Export$=format$("{0}({1}) = {2}",b$,i+1, trim$(a$(i)))+nl$
next
else
Export$=b$+" = "+a$+nl$
end if
end if
End Sub
}
valid=list:="FULLNAME", "FAVOURITEFRUIT", "NEEDSPEELING", "SEEDSREMOVED", "OTHERFAMILY"
binary{
UEsDBBQAAAgIAO8FflU2rdfqSAIAANQDAAARAAAAY29uZmlndXJhdGlvbi50eHRT
VgjJyCxWyCxWSFRIzs9Ly0wvLUosyczPU0jLzElVyMxTKC5JzEtJLErBJp2WX5Sb
WMLLpczLpazgk5mXWqyQlJqemZeXmZeuUJ5ZkqGQqJCRWJyhkF+kkKhQnJqbmZyf
k5+nkFiUqpCZnpdflJqikFSpUJKRqpBYUJCTmQw2G2RYQVF+elFirp6CU05iXrZC
DthskLbEnOJ8PHrhGnm5QMbAPAdSlVaak5OXmJuqUJBYlJibWpJaxMvlFurj4+fo
66rglp+v4JRYlAQSRNaYqJCWWJZfWpRZkqqQVlSaWcLL5eYY5h8a5Bni6hYU6hmi
kJSYl5iXiK4rKT8/JzUxT6EkI7FEoTgjvzQnRSEpVaE4tYSXy8/V1SU4wNXVx9PP
HUkfTEtmsUJyfm5ual5JaopCfmkJL5e1QjBIS5Crr3+YqwtEizNKbOQXgCmQ9yDB
lJdfopCcWAyyMa84sySzLFVHIam0BC0SkUJCWSElsSQRbDmKNoXEvBSF3MRKkOsL
ilKLU4vKiAl4R5ibEnMUUgtLE3OKFYoz0/MUkhPzQCaVFqemKJTkKxSngpxQkorL
XWBHgcxLK8rPBVuJ5FM9eHinFOUXFCCcVZBYVJxapKcAdQqa4VATQH4qScxOVcgt
zSnJLMhBShfFcHeBjQTFRmKxHjiNpyamgNI2KFBKihIzc8AJPSOzJLW4IDE5VSGx
KL80LwXJ/dAYQREDB3RaZmpOSjHITPyZASVc/UM8XIPcHH09fSIVgjJKoSlWR8Ej
saioEp5+AVBLAQItABQAAAgIAO8FflU2rdfqSAIAANQDAAARAAAAAAAAAAAAIAAA
AAAAAABjb25maWd1cmF0aW9uLnR4dFBLBQYAAAAAAQABAD8AAAB3AgAAAAA=} as zip1
Declare zip compressor
method zip,"OpenZipBuf", zip1
method zip, "ExtractOneToBuffer", "configuration.txt" as buf
If true then
// save buf to file, the load to document as ANSI 1033
open "configuration.txt" for output as #f
put #f,buf, 1
close #f
document b$ : Load.doc b$, "configuration.txt", 1033
check b$, valid
else
check chr$(eval$(buf)), valid
end if
</syntaxhighlight>
{{out}}
<pre>FULLNAME = Foo Barber
FAVOURITEFRUIT = banana
NEEDSPEELING = true
SEEDSREMOVED = false
OTHERFAMILY(1) = Rhu Barber
OTHERFAMILY(2) = Harry Barber
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[CreateVar, ImportConfig];
CreateVar[x_, y_String: "True"] := Module[{},
If[StringFreeQ[y, ","]
Line 2,685 ⟶ 3,419:
CreateVar @@@ data;
]
ImportConfig[file]</syntaxhighlight>
</lang>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 2,692 ⟶ 3,425:
This is defined as a function, parameters are returned as part of a struct. When the first line, and the assignment to return values are removed, it is a script that stores the parameters in the local workspace.
 
<langsyntaxhighlight MATLABlang="matlab">function R = readconf(configfile)
% READCONF reads configuration file.
%
Line 2,730 ⟶ 3,463:
fclose(fid);
whos, % shows the parameter in the local workspace
</langsyntaxhighlight>
 
<pre>R=readconf('file.conf')
Line 2,767 ⟶ 3,500:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight lang="nanoquery">import Nanoquery.IO
import dict
 
Line 2,808 ⟶ 3,541:
end
 
println get_config(args[2])</langsyntaxhighlight>
{{out}}
<pre>[[FULLNAME : Foo Barber], [FAVOURITEFRUIT : banana], [NEEDSPEELING : true], [OTHERFAMILY : [Rhu Barber, Harry Barber]]]</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import re, strformat, strutils, tables
 
var configs: OrderedTable[string, seq[string]]
var parsed: seq[string]
 
for line in "demo.config".lines():
let line = line.strip()
if line != "" and not line.startswith(re"#|;"):
parsed = line.split(re"\s*=\s*|\s+", 1)
configs[parsed[0].toLower()] = if len(parsed) > 1: parsed[1].split(re"\s*,\s*") else: @[]
 
for key in ["fullname", "favouritefruit", "needspeeling", "seedsremoved", "otherfamily"]:
if not configs.hasKey(key):
echo(&"{key} = false")
else:
case len(configs[key])
of 0:
echo(&"{key} = true")
of 1:
echo(&"{key} = {configs[key][0]}")
else:
for i, v in configs[key].pairs():
echo(&"{key}({i+1}) = {v}")</syntaxhighlight>
{{out}}
<pre>
fullname = Foo Barber
favouritefruit = banana
needspeeling = true
seedsremoved = false
otherfamily(1) = Rhu Barber
otherfamily(2) = Harry Barber
</pre>
 
=={{header|OCaml}}==
Line 2,816 ⟶ 3,583:
Using the library [http://homepage.mac.com/letaris/ ocaml-inifiles]:
 
<langsyntaxhighlight lang="ocaml">#use "topfind"
#require "inifiles"
open Inifiles
Line 2,840 ⟶ 3,607:
print_endline "other family:";
List.iter (Printf.printf "- %s\n") v;
;;</langsyntaxhighlight>
 
The file "conf.ini":
Line 2,886 ⟶ 3,653:
=={{header|ooRexx}}==
Here's another way of doing this, which stores the values in a Rexx stem (array), and stores each value of a multivalued variable as a separate item:
<syntaxhighlight lang="oorexx">
<lang ooRexx>
#!/usr/bin/rexx
/*.----------------------------------------------------------------------.*/
Line 3,048 ⟶ 3,815:
end
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,070 ⟶ 3,837:
This solution makes use of FCL-STL package shipped with FPC >= 2.6.0, moreover it can be run directly like a script (just chmod +x) using the new instantfpc feature.
 
<langsyntaxhighlight Pascallang="pascal">#!/usr/bin/instantfpc
 
{$if not defined(fpc) or (fpc_fullversion < 20600)}
Line 3,169 ⟶ 3,936:
ConfigValues.Free;
ConfigStrings.Free;
end.</langsyntaxhighlight>
 
{{out}}
Line 3,189 ⟶ 3,956:
What we end up with after processing rosetta.config are three VARs and a LST, named FAVOURITEFRUIT, FULLNAME, NEEDSPEELING and OTHERFAMILY respectively.
 
<langsyntaxhighlight lang="sgml"><@ DEFUDRLIT>__ReadConfigurationFile|
<@ LETSCPPNTPARSRC>Data|1</@><@ OMT> read file into locally scope variable</@>
<@ LETCGDLSTLLOSCP>List|Data</@><@ OMT> split Data into a list of lines </@>
Line 3,216 ⟶ 3,983:
<@ SAYVAR>NEEDSPEELING</@>
<@ SAYDMPLST>OTHERFAMILY</@>
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
Line 3,222 ⟶ 3,989:
This is an all-singing, all-dancing version that checks the configuration file syntax and contents and raises exceptions if it fails. (It is intentionally over-commented for pedagogical purposes.)
<langsyntaxhighlight lang="perl">my $fullname;
my $favouritefruit;
my $needspeeling;
Line 3,299 ⟶ 4,066:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Phix}}==
Normally I would recommend IupConfig, but the "standard" file format in the task description isn't even close (no [Section] headers, no '=').
<lang Phix>integer fn = open("RCTEST.INI","r")
sequence lines = get_text(fn,GT_LF_STRIPPED)
close(fn)
constant dini = new_dict()
for i=1 to length(lines) do
string li = trim(lines[i])
if length(li)
and not find(li[1],"#;") then
integer k = find(' ',li)
if k!=0 then
string rest = li[k+1..$]
li = li[1..k-1] -- (may want upper())
if find(',',rest) then
sequence a = split(rest,',')
for j=1 to length(a) do a[j]=trim(a[j]) end for
putd(li,a,dini)
else
putd(li,rest,dini)
end if
else
putd(li,1,dini) -- ""
end if
end if
end for
 
<!--<syntaxhighlight lang="phix">-->
function visitor(object key, object data, object /*user_data*/)
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"RCTEST.INI"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"r"</span><span style="color: #0000FF;">)</span>
?{key,data}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">lines</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #004600;">GT_LF_STRIPPED</span><span style="color: #0000FF;">)</span>
return 1
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">constant</span> <span style="color: #000000;">dini</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">()</span>
traverse_dict(routine_id("visitor"),0,dini)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
?getd("FAVOURITEFRUIT",dini)</lang>
<span style="color: #004080;">string</span> <span style="color: #000000;">li</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">li</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">and</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">li</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"#;"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">li</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">rest</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">li</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$]</span>
<span style="color: #000000;">li</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">li</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">k</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- (may want upper())</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">','</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rest</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rest</span><span style="color: #0000FF;">,</span><span style="color: #008000;">','</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]=</span><span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">putd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">li</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dini</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">putd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">li</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dini</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">putd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">li</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dini</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- ""</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">visitor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000080;font-style:italic;">/*user_data*/</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?{</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">data</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"visitor"</span><span style="color: #0000FF;">),</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dini</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"FAVOURITEFRUIT"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dini</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
 
{{out}}
<pre>
Line 3,344 ⟶ 4,115:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def optionValue
2 get "," find
if
Line 3,403 ⟶ 4,174:
drop
endfor
endif</langsyntaxhighlight>
{{out}}
<pre>FULLNAME = Foo Barber
Line 3,416 ⟶ 4,187:
Slightly modify the format of the configuration file before passing it to the internal function parse_ini_string()
 
<langsyntaxhighlight PHPlang="php"><?php
 
$conf = file_get_contents('parse-conf-file.txt');
Line 3,450 ⟶ 4,221:
echo 'Need spelling = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;
echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;
echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;</langsyntaxhighlight>
 
{{out}}
Line 3,462 ⟶ 4,233:
[1] => Harry Barber
)</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
Vars = ["fullname","favouritefruit","needspeeling","seedsremoved","otherfamily"],
Config = read_config("read_a_configuration_file_config.cfg"),
foreach(Key in Vars)
printf("%w = %w\n", Key, Config.get(Key,false))
end,
nl.
 
% Read configuration file
read_config(File) = Config =>
Config = new_map(),
Lines = [Line : Line in read_file_lines(File), Line != [], not membchk(Line[1],"#;")],
foreach(Line in Lines)
Line := strip(Line),
once( append(Key,[' '|Value],Line) ; Key = Line, Value = true),
if find(Value,",",_,_) then
Value := [strip(Val) : Val in split(Value,",")]
end,
Key := strip(to_lowercase(Key)),
Config.put(Key,Value)
end.</syntaxhighlight>
 
{{out}}
<pre>fullname = Foo Barber
favouritefruit = banana
needspeeling = true
seedsremoved = false
otherfamily = [Rhu Barber,Harry Barber]</pre>
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de rdConf (File)
(in File
(while (read)
Line 3,471 ⟶ 4,273:
(rdConf "conf.txt")
(println FULLNAME FAVOURITEFRUIT NEEDSPEELING SEEDSREMOVED OTHERFAMILY)
(bye)</langsyntaxhighlight>
{{out}}
<pre>"Foo Barber" "banana" T NIL "Rhu Barber, Harry Barber"</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
set: procedure options (main);
declare text character (100) varying;
Line 3,535 ⟶ 4,337:
 
end set;
</syntaxhighlight>
</lang>
{{out}} using the given text file as input:-
<pre>
Line 3,547 ⟶ 4,349:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Read-ConfigurationFile
{
Line 3,616 ⟶ 4,418:
Write-Verbose -Message ("{0,-15}= {1}" -f "OTHERFAMILY", ($script:otherFamily -join ", "))
}
</syntaxhighlight>
</lang>
I stored the file in ".\temp.txt" and there is no output unless the -Verbose switch is used:
<syntaxhighlight lang="powershell">
<lang PowerShell>
Read-ConfigurationFile -Path .\temp.txt -Verbose
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,630 ⟶ 4,432:
</pre>
Test if the variables are set:
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-Variable -Name fullName, favouriteFruit, needsPeeling, seedsRemoved, otherFamily
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,645 ⟶ 4,447:
 
=== Using Switch -Regex ===
<syntaxhighlight lang="powershell">
<lang PowerShell>
Function Read-ConfigurationFile {
[CmdletBinding()]
Line 3,734 ⟶ 4,536:
Return $__Aux
}
</syntaxhighlight>
</lang>
Setting variable
<syntaxhighlight lang="powershell">
<lang PowerShell>
$Configuration = Read-ConfigurationFile -LiteralPath '.\config.cfg'
</syntaxhighlight>
</lang>
 
Show variable
<syntaxhighlight lang="powershell">
<lang PowerShell>
$Configuration
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,755 ⟶ 4,557:
 
Using customize function
<syntaxhighlight lang="powershell">
<lang PowerShell>
Show-Value $Configuration 'fullname'
Show-Value $Configuration 'favouritefruit'
Line 3,764 ⟶ 4,566:
Show-Value $Configuration 'otherfamily' 1
Show-Value $Configuration 'otherfamily' 2
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,778 ⟶ 4,580:
 
Using index variable
<syntaxhighlight lang="powershell">
<lang PowerShell>
'$Configuration[''fullname'']'
$Configuration['fullname']
Line 3,824 ⟶ 4,626:
'=== $Configuration.Item(3).Item(1) ==='
$Configuration.Item(3).Item(1)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,881 ⟶ 4,683:
=={{header|Python}}==
This task is not well-defined, so we have to make some assumptions (see comments in code).
<langsyntaxhighlight lang="python">def readconf(fn):
ret = {}
with file(fn) as fp:
Line 3,914 ⟶ 4,716:
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 3,920 ⟶ 4,722:
Use the shared [[Racket/Options]] code.
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 3,932 ⟶ 4,734:
(printf "seedsremoved = ~s\n" seedsremoved)
(printf "otherfamily = ~s\n" otherfamily)
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,947 ⟶ 4,749:
{{works with|Rakudo|2020.08.1}}
This demonstrates several interesting features of Raku, including full grammar support, derived grammars, alternation split across derivations, and longest-token matching that works across derivations. It also shows off Raku's greatly cleaned up regex syntax.
<syntaxhighlight lang="raku" perl6line>my $fullname;
my $favouritefruit;
my $needspeeling = False;
Line 3,996 ⟶ 4,798:
say "needspeeling: $needspeeling";
say "seedsremoved: $seedsremoved";
print "otherfamily: "; say @otherfamily.raku;</langsyntaxhighlight>
{{out}}
<pre>fullname: Foo Barber
Line 4,006 ⟶ 4,808:
 
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
<lang vb>
type TSettings extends QObject
FullName as string
Line 4,066 ⟶ 4,868:
 
Call ReadSettings
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,076 ⟶ 4,878:
Settings.OtherFamily.Item(0) = Rhu Barber
Settings.OtherFamily.Item(1) = Harry Barber
</pre>
=={{header|Red}}==
<syntaxhighlight lang="rebol">Red ["Read a config file"]
 
remove-each l lines: read/lines %file.conf [any [empty? l #"#" = l/1]]
foreach line lines [
foo: parse line [collect [keep to [" " | end] skip keep to end]]
either foo/1 = #";" [set to-word foo/2 false][
set to-word foo/1 any [
all [find foo/2 #"," split foo/2 ", "]
foo/2
true
]
]
]
foreach w [fullname favouritefruit needspeeling seedsremoved otherfamily][
prin [pad w 15 ": "] probe get w
]</syntaxhighlight>
 
{{out}}
<pre>fullname : "Foo Barber"
favouritefruit : "banana"
needspeeling : true
seedsremoved : false
otherfamily : ["Rhu Barber" "Harry Barber"]
</pre>
 
Line 4,081 ⟶ 4,908:
No assumptions were made about what variables are (or aren't) in the configuration file.
<br>Code was written to make the postmortem report as readable as possible.
<langsyntaxhighlight lang="rexx">/*REXX program reads a config (configuration) file and assigns VARs as found within. */
signal on syntax; signal on novalue /*handle REXX source program errors. */
parse arg cFID _ . /*cFID: is the CONFIG file to be read.*/
Line 4,127 ⟶ 4,954:
novalue: syntax: call err 'REXX program' condition('C') "error",,
condition('D'),'REXX source statement (line' sigl"):",sourceline(sigl)
</syntaxhighlight>
</lang>
'''output''' &nbsp; when using the input (file) as specified in the task description:
<pre>
Line 4,144 ⟶ 4,971:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">fullname = favouritefruit = ""
needspeeling = seedsremoved = false
otherfamily = []
Line 4,168 ⟶ 4,995:
otherfamily.each_with_index do |name, i|
puts "otherfamily(#{i+1}) = #{name}"
end</langsyntaxhighlight>
 
{{out}}
Line 4,181 ⟶ 5,008:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">dim param$(6)
dim paramVal$(6)
param$(1) = "fullname"
Line 4,216 ⟶ 5,043:
print param$(i);chr$(9);paramVal$(i)
end if
next i</langsyntaxhighlight>
{{out}}
<pre>
Line 4,228 ⟶ 5,055:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
Line 4,307 ⟶ 5,134:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,322 ⟶ 5,149:
* Converts the entire collection to a Map
 
<langsyntaxhighlight Scalalang="scala">val conf = scala.io.Source.fromFile("config.file").
getLines.
toList.
Line 4,331 ⟶ 5,158:
map {
s:List[String] => (s(0).toLowerCase, s(1).split(",").map(_.trim).toList)
}.toMap</langsyntaxhighlight>
 
Test code:
<syntaxhighlight lang="scala">
<lang Scala>
for ((k,v) <- conf) {
if (v.size == 1)
Line 4,343 ⟶ 5,170:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,360 ⟶ 5,187:
and [http://seed7.sourceforge.net/libraries/scanfile.htm#getLine%28inout_file%29 getLine].
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "scanfile.s7i";
 
Line 4,408 ⟶ 5,235:
writeln(("otherfamily[" <& index <& "]:") rpad 16 <& otherfamily[index]);
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,421 ⟶ 5,248:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">
// read the configuration file and get a list of just the interesting lines
set lines to each line of file "config.txt" where char 1 of each isn't in ("#", ";", "")
Line 4,440 ⟶ 5,267:
put "Variable" && name && "is" && value(name)
end repeat
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="sensetalk">
Variable FULLNAME is Foo Barber
Variable FAVOURITEFRUIT is banana
Variable NEEDSPEELING is True
Variable OTHERFAMILY is ("Rhu Barber","Harry Barber")
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var fullname = (var favouritefruit = "");
var needspeeling = (var seedsremoved = false);
var otherfamily = [];
Line 4,476 ⟶ 5,303:
otherfamily.each_kv {|i, name|
say "otherfamily(#{i+1}) = #{name}";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,490 ⟶ 5,317:
{{works with|Smalltalk/X}}
This code retrieves the configuration values as a Dictionary; code to set an object's instance variables follows below:
<langsyntaxhighlight lang="smalltalk">dict := Dictionary new.
configFile asFilename readingLinesDo:[:line |
(line isEmpty or:[ line startsWithAnyOf:#('#' ';') ]) ifFalse:[
Line 4,508 ⟶ 5,335:
]
].
]</langsyntaxhighlight>
gives us in dict Dictionary ('fullname'->'Foo Barber' 'needspeeling'->true 'favouritefruit'->'banana' 'otherfamily'->OrderedCollection('Rhu Barber' 'Harry Barber'))
 
assuming that the target object has setters for each option name, we could write:
<langsyntaxhighlight lang="smalltalk">dict keysAndValuesDo:[:eachOption :eachValue |
someObject
perform:(eachOption,':') asSymbol with:eachValue
ifNotUnderstood: [ self error: 'unknown option: ', eachOption ]
]</langsyntaxhighlight>
or assign variables with:
<langsyntaxhighlight lang="smalltalk">fullname := dict at: 'fullname' ifAbsent:false.
needspeeling := dict at: 'needspeeling' ifAbsent:false.
favouritefruit := dict at: 'favouritefruit' ifAbsent:false.
otherfamily := dict at: 'otherfamily' ifAbsent:false.
seedsremoved := dict at: 'seedsremoved' ifAbsent:false.
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
This code stores the configuration values in a global array (<code>cfg</code>) so they can't pollute the global namespace in unexpected ways.
<langsyntaxhighlight lang="tcl">proc readConfig {filename {defaults {}}} {
global cfg
# Read the file in
Line 4,572 ⟶ 5,399:
puts "Peeling? $cfg(needspeeling)"
puts "Unseeded? $cfg(seedsremoved)"
puts "Family: $cfg(otherfamily)"</langsyntaxhighlight>
 
=={{header|TXR}}==
Prove the logic by transliterating to a different syntax:
<langsyntaxhighlight lang="txr">@(collect)
@ (cases)
#@/.*/
Line 4,600 ⟶ 5,427:
@ (end)
@(end)
</syntaxhighlight>
</lang>
 
Sample run:
Line 4,616 ⟶ 5,443:
 
{{works with|bash}}
<langsyntaxhighlight lang="bash">readconfig() (
# redirect stdin to read from the given filename
exec 0<"$1"
Line 4,659 ⟶ 5,486:
for i in "${!otherfamily[@]}"; do
echo "otherfamily[$i] = ${otherfamily[i]}"
done</langsyntaxhighlight>
 
{{out}}
Line 4,670 ⟶ 5,497:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Set ofso = CreateObject("Scripting.FileSystemObject")
Set config = ofso.OpenTextFile(ofso.GetParentFolderName(WScript.ScriptFullName)&"\config.txt",1)
Line 4,709 ⟶ 5,536:
config.Close
Set ofso = Nothing
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,723 ⟶ 5,550:
=={{header|Vedit macro language}}==
 
<langsyntaxhighlight lang="vedit">#11 = 0 // needspeeling = FALSE
#12 = 0 // seedsremoved = FALSE
Reg_Empty(21) // fullname
Line 4,757 ⟶ 5,584:
Message("fullname = ") Reg_Type(21) TN
Message("favouritefruit = ") Reg_Type(22) TN
Message("otherfamily = ") Reg_Type(23) TN</langsyntaxhighlight>
 
{{out}}
Line 4,770 ⟶ 5,597:
=={{header|Visual Basic}}==
 
<langsyntaxhighlight lang="vb">' Configuration file parser routines.
'
' (c) Copyright 1993 - 2011 Mark Hobley
Line 4,974 ⟶ 5,801:
Public Function btrim$(arg$)
btrim$ = LTrim$(RTrim$(arg$))
End Function</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-ioutil}}
Includes 'seeds removed' in the map (with a default value of false) even though it's commented out of the configuration file.
<syntaxhighlight lang="wren">import "io" for File
import "./ioutil" for FileUtil
 
class Configuration {
construct new(map) {
_fullName = map["fullName"]
_favouriteFruit = map["favouriteFruit"]
_needsPeeling = map["needsPeeling"]
_seedsRemoved = map["seedsRemoved"]
_otherFamily = map["otherFamily"]
}
 
toString {
return [
"Full name = %(_fullName)",
"Favourite fruit = %(_favouriteFruit)",
"Needs peeling = %(_needsPeeling)",
"Seeds removed = %(_seedsRemoved)",
"Other family = %(_otherFamily)"
].join("\n")
}
}
 
var commentedOut = Fn.new { |line| line.startsWith("#") || line.startsWith(";") }
 
var toMapEntry = Fn.new { |line|
var ix = line.indexOf(" ")
if (ix == -1) return MapEntry.new(line, "")
return MapEntry.new(line[0...ix], line[ix+1..-1])
}
 
var fileName = "configuration.txt"
var lines = File.read(fileName).trimEnd().split(FileUtil.lineBreak)
var mapEntries = lines.map { |line| line.trim() }.
where { |line| line != "" }.
where { |line| !commentedOut.call(line) }.
map { |line| toMapEntry.call(line) }
var configurationMap = { "needsPeeling": false, "seedsRemoved": false }
for (me in mapEntries) {
if (me.key == "FULLNAME") {
configurationMap["fullName"] = me.value
} else if (me.key == "FAVOURITEFRUIT") {
configurationMap["favouriteFruit"] = me.value
} else if (me.key == "NEEDSPEELING") {
configurationMap["needsPeeling"] = true
} else if (me.key == "OTHERFAMILY") {
configurationMap["otherFamily"] = me.value.split(" , ").map { |s| s.trim() }.toList
} else if (me.key == "SEEDSREMOVED") {
configurationMap["seedsRemoved"] = true
} else {
System.print("Encountered unexpected key %(me.key)=%(me.value)")
}
}
System.print(Configuration.new(configurationMap))</syntaxhighlight>
 
{{out}}
<pre>
Full name = Foo Barber
Favourite fruit = banana
Needs peeling = true
Seeds removed = false
Other family = [Rhu Barber, Harry Barber]
</pre>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">a = open("rosetta_read.cfg")
 
while(not eof(#a))
Line 5,012 ⟶ 5,907:
wend
 
close #a</langsyntaxhighlight>
 
=={{header|zkl}}==
First, a simple parser that knows nothing about contents, just format.
<langsyntaxhighlight lang="zkl">fcn readConfigFile(config){ //--> read only dictionary
conf:=Dictionary();
foreach line in (config){
Line 5,034 ⟶ 5,929:
}
 
conf:=readConfigFile(File("foo.conf"));</langsyntaxhighlight>
Which may be good enough; query the hash table to get a set option or a default if it wasn't set:
<langsyntaxhighlight lang="zkl">foreach k,v in (conf){ println(k," : ",v) }
println("Value of seedsremoved = ",conf.find("seedsremoved",False));</langsyntaxhighlight>
{{out}}
<pre>
Line 5,047 ⟶ 5,942:
</pre>
If your program actually wants to use the options as variables, the following sets variables to values in the config file, ignoring misspellings, or values you don't care about. You are not allowed to create variables "on the fly".
<langsyntaxhighlight lang="zkl">var needspeeling,otherfamily,favouritefruit,fullname,seedsremoved;
foreach k,v in (conf){ try{ setVar(k,v) }catch{} };
foreach k,v in (vars){ println(k," : ",v) }
println("Value of seedsremoved = ",seedsremoved);</langsyntaxhighlight>
{{out}}
<pre>
Line 5,065 ⟶ 5,960:
{{omit from|Lilypond}}
{{omit from|Openscad}}
{{omit from|Z80 Assembly|Label names do not exist at runtime.}}
 
[[Category:Initialization]]
9,476

edits