Read a configuration file: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 57:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F readconf(fname)
[String = String] ret
L(=line) File(fname).read_lines()
Line 84:
V conf = readconf(‘config.txt’)
L(k, v) sorted(conf.items())
print(k‘ = ’v)</langsyntaxhighlight>
 
{{out}}
Line 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 116:
Put_Line("seedsremoved = " & Boolean'Image(seedsremoved));
Put_Line("otherfamily = " & otherfamily);
end;</langsyntaxhighlight>
 
{{out}}
Line 127:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">record r, s;
integer c;
file f;
Line 184:
l.ucall(o_, 0, ", ");
o_("\n");
}</langsyntaxhighlight>
{{Out}}
<pre>FAVOURITEFRUIT: banana
Line 194:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">parseConfig: function [f][
lines: split.lines read f
lines: select map lines 'line [strip replace line {/[#;].*/} ""]
Line 220:
if? block? v -> print [k "->" join.with:", " v]
else -> print [k "->" v]
]</langsyntaxhighlight>
 
{{out}}
Line 231:
=={{header|AutoHotkey}}==
 
<syntaxhighlight lang="autohotkey">
<lang AutoHotkey>
; Author: AlephX, Aug 18 2011
data = %A_scriptdir%\rosettaconfig.txt
Line 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 306:
return(str)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 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 578:
 
END FUNCTION
</syntaxhighlight>
</lang>
Run
<pre>
Line 604:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> BOOL = 1
NAME = 2
ARRAY = 3
Line 664:
WHEN ARRAY: = !^array$()
ENDCASE
= 0</langsyntaxhighlight>
{{out}}
<pre>
Line 680:
'''optimized'''
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 850:
return 0;
 
}</langsyntaxhighlight>
 
{{out}}
Line 866:
'''unoptimized'''
 
<langsyntaxhighlight lang="cpp">#include "stdafx.h"
#include <iostream>
#include <fstream>
Line 971:
return 0;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 981:
 
'''Solution without Boost libraries. No optimisation.'''
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <iomanip>
#include <string>
Line 1,056:
read_config(inp,outp);
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,066:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns read-conf-file.core
(:require [clojure.java.io :as io]
[clojure.string :as str])
Line 1,113:
(defn -main
[filename]
(output conf-keys (mk-conf (get-lines filename))))</langsyntaxhighlight>
 
{{out}}
Line 1,125:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol">
identification division.
program-id. ReadConfiguration.
Line 1,222:
end-perform
.
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,236:
=={{header|Common Lisp}}==
Using parser-combinators available in quicklisp:
<langsyntaxhighlight lang="lisp">(ql:quickload :parser-combinators)
 
(defpackage :read-config
Line 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,289:
NIL
NIL
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.regex, std.getopt;
 
enum VarName(alias var) = var.stringof.toUpper;
Line 1,327:
writefln("%14s = %s", VarName!seedsRemoved, seedsRemoved);
writefln("%14s = %s", VarName!otherFamily, otherFamily);
}</langsyntaxhighlight>
{{out}}
<pre> FULLNAME = Foo Barber
Line 1,336:
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ open input config.ini
$ loop:
$ read /end_of_file = done input line
Line 1,353:
$ goto loop
$ done:
$ close input</langsyntaxhighlight>
{{out}}
<pre>$ @read_a_configuration_file
Line 1,363:
{{libheader| uSettings}}
Unit for manager config files, used in [[Update a configuration file]].
<syntaxhighlight lang="delphi">
<lang Delphi>
unit uSettings;
 
Line 1,582:
end;
end.
</syntaxhighlight>
</lang>
Usage of unit:
<syntaxhighlight lang="delphi">
<lang Delphi>
program ReadAConfigFile;
 
Line 1,613:
Settings.Free;
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>FAVOURITEFRUIT = banana
Line 1,624:
{{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,640:
; 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,652:
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,690:
end
 
Configuration_file.task</langsyntaxhighlight>
 
{{out}}
Line 1,704:
=={{header|Erlang}}==
 
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( configuration_file ).
 
Line 1,726:
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,740:
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,801:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
Line 1,811:
 
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,852:
CR ." Family:"
CR otherfamily(1) $.
CR otherfamily(2) $. ;</langsyntaxhighlight>
The config file would look like this
<pre>
Line 1,881:
=={{header|Fortran}}==
 
<syntaxhighlight lang="fortran">
<lang Fortran>
program readconfig
implicit none
Line 1,990:
 
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 2,088:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,101:
 
=={{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 2,116:
Print fullname
 
End</langsyntaxhighlight>
Output:
<pre>
Line 2,125:
=={{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 2,284:
 
return v, nil
}</langsyntaxhighlight>
 
Usage example:
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,349:
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,366:
}
}
}</langsyntaxhighlight>
Testing:
<langsyntaxhighlight lang="groovy">loadConfig new File('config.ini')
config.each { println it }</langsyntaxhighlight>
{{out}}
<pre>FULLNAME=Foo Barber
Line 2,380:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">
import Data.Char
import Data.List
Line 2,414:
defaultConfig :: Config
defaultConfig = Config "" "" False False []
</syntaxhighlight>
</lang>
 
Or, use Data.Configfile:
 
<langsyntaxhighlight lang="haskell">
import Data.ConfigFile
import Data.Either.Utils
Line 2,427:
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,438:
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,467:
write(s[1:-2])
}
end</langsyntaxhighlight>
 
Sample run on above input:
Line 2,483:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">require'regex'
set=:4 :'(x)=:y'
 
Line 2,504:
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,586:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,593:
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,633:
return result;
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,641:
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,666:
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,679:
]
}
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 2,685:
 
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,706:
end);
 
parse</langsyntaxhighlight>
 
'''Invocation'''
Line 2,726:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function readconf(file)
vars = Dict()
for line in eachline(file)
Line 2,749:
readconf("test.conf")
 
@show fullname favouritefruit needspeeling otherfamily</langsyntaxhighlight>
 
{{out}}
Line 2,761:
{{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,797:
private fun toKeyValuePair(line: String) = line.split(Regex(" "), 2).let {
Pair(it[0], if (it.size == 1) "" else it[1])
}</langsyntaxhighlight>
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 2,934:
done
done
</syntaxhighlight>
</lang>
{{out}}<pre>
fullname = Foo Barber
Line 2,945:
 
=={{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 3,014:
'<br />'
#otherfamily
'<br />'</langsyntaxhighlight>
{{out}}
<pre>Foo Barber
Line 3,023:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
dim confKeys$(100)
dim confValues$(100)
Line 3,093:
next i
end function
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,106:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">conf = {}
 
fp = io.open( "conf.txt", "r" )
Line 3,145:
print( "", entry )
end
end</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[CreateVar, ImportConfig];
CreateVar[x_, y_String: "True"] := Module[{},
If[StringFreeQ[y, ","]
Line 3,168:
CreateVar @@@ data;
]
ImportConfig[file]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 3,174:
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 3,212:
fclose(fid);
whos, % shows the parameter in the local workspace
</langsyntaxhighlight>
 
<pre>R=readconf('file.conf')
Line 3,249:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight lang="nanoquery">import Nanoquery.IO
import dict
 
Line 3,290:
end
 
println get_config(args[2])</langsyntaxhighlight>
{{out}}
<pre>[[FULLNAME : Foo Barber], [FAVOURITEFRUIT : banana], [NEEDSPEELING : true], [OTHERFAMILY : [Rhu Barber, Harry Barber]]]</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import re, strformat, strutils, tables
 
var configs: OrderedTable[string, seq[string]]
Line 3,317:
else:
for i, v in configs[key].pairs():
echo(&"{key}({i+1}) = {v}")</langsyntaxhighlight>
{{out}}
<pre>
Line 3,332:
Using the library [http://homepage.mac.com/letaris/ ocaml-inifiles]:
 
<langsyntaxhighlight lang="ocaml">#use "topfind"
#require "inifiles"
open Inifiles
Line 3,356:
print_endline "other family:";
List.iter (Printf.printf "- %s\n") v;
;;</langsyntaxhighlight>
 
The file "conf.ini":
Line 3,402:
=={{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,564:
end
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,586:
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,685:
ConfigValues.Free;
ConfigStrings.Free;
end.</langsyntaxhighlight>
 
{{out}}
Line 3,705:
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,732:
<@ SAYVAR>NEEDSPEELING</@>
<@ SAYDMPLST>OTHERFAMILY</@>
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
Line 3,738:
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,815:
}
}
</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 '=').
 
<!--<langsyntaxhighlight Phixlang="phix">-->
<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>
<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>
Line 3,852:
<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>
<!--</langsyntaxhighlight>-->
 
{{out}}
Line 3,864:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def optionValue
2 get "," find
if
Line 3,923:
drop
endfor
endif</langsyntaxhighlight>
{{out}}
<pre>FULLNAME = Foo Barber
Line 3,936:
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,970:
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,984:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
Vars = ["fullname","favouritefruit","needspeeling","seedsremoved","otherfamily"],
Config = read_config("read_a_configuration_file_config.cfg"),
Line 4,004:
Key := strip(to_lowercase(Key)),
Config.put(Key,Value)
end.</langsyntaxhighlight>
 
{{out}}
Line 4,015:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de rdConf (File)
(in File
(while (read)
Line 4,022:
(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 4,086:
 
end set;
</syntaxhighlight>
</lang>
{{out}} using the given text file as input:-
<pre>
Line 4,098:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Read-ConfigurationFile
{
Line 4,167:
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 4,181:
</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 4,196:
 
=== Using Switch -Regex ===
<syntaxhighlight lang="powershell">
<lang PowerShell>
Function Read-ConfigurationFile {
[CmdletBinding()]
Line 4,285:
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 4,306:
 
Using customize function
<syntaxhighlight lang="powershell">
<lang PowerShell>
Show-Value $Configuration 'fullname'
Show-Value $Configuration 'favouritefruit'
Line 4,315:
Show-Value $Configuration 'otherfamily' 1
Show-Value $Configuration 'otherfamily' 2
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,329:
 
Using index variable
<syntaxhighlight lang="powershell">
<lang PowerShell>
'$Configuration[''fullname'']'
$Configuration['fullname']
Line 4,375:
'=== $Configuration.Item(3).Item(1) ==='
$Configuration.Item(3).Item(1)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,432:
=={{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 4,465:
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 4,471:
Use the shared [[Racket/Options]] code.
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 4,483:
(printf "seedsremoved = ~s\n" seedsremoved)
(printf "otherfamily = ~s\n" otherfamily)
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,498:
{{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 4,547:
say "needspeeling: $needspeeling";
say "seedsremoved: $seedsremoved";
print "otherfamily: "; say @otherfamily.raku;</langsyntaxhighlight>
{{out}}
<pre>fullname: Foo Barber
Line 4,557:
 
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
<lang vb>
type TSettings extends QObject
FullName as string
Line 4,617:
 
Call ReadSettings
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,629:
</pre>
=={{header|Red}}==
<langsyntaxhighlight Rebollang="rebol">Red ["Read a config file"]
 
remove-each l lines: read/lines %file.conf [any [empty? l #"#" = l/1]]
Line 4,644:
foreach w [fullname favouritefruit needspeeling seedsremoved otherfamily][
prin [pad w 15 ": "] probe get w
]</langsyntaxhighlight>
 
{{out}}
Line 4,657:
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,703:
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,720:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">fullname = favouritefruit = ""
needspeeling = seedsremoved = false
otherfamily = []
Line 4,744:
otherfamily.each_with_index do |name, i|
puts "otherfamily(#{i+1}) = #{name}"
end</langsyntaxhighlight>
 
{{out}}
Line 4,757:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">dim param$(6)
dim paramVal$(6)
param$(1) = "fullname"
Line 4,792:
print param$(i);chr$(9);paramVal$(i)
end if
next i</langsyntaxhighlight>
{{out}}
<pre>
Line 4,804:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
Line 4,883:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,898:
* Converts the entire collection to a Map
 
<langsyntaxhighlight Scalalang="scala">val conf = scala.io.Source.fromFile("config.file").
getLines.
toList.
Line 4,907:
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,919:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,936:
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,984:
writeln(("otherfamily[" <& index <& "]:") rpad 16 <& otherfamily[index]);
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,997:
 
=={{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 5,016:
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 5,052:
otherfamily.each_kv {|i, name|
say "otherfamily(#{i+1}) = #{name}";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,066:
{{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 5,084:
]
].
]</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 5,148:
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 5,176:
@ (end)
@(end)
</syntaxhighlight>
</lang>
 
Sample run:
Line 5,192:
 
{{works with|bash}}
<langsyntaxhighlight lang="bash">readconfig() (
# redirect stdin to read from the given filename
exec 0<"$1"
Line 5,235:
for i in "${!otherfamily[@]}"; do
echo "otherfamily[$i] = ${otherfamily[i]}"
done</langsyntaxhighlight>
 
{{out}}
Line 5,246:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Set ofso = CreateObject("Scripting.FileSystemObject")
Set config = ofso.OpenTextFile(ofso.GetParentFolderName(WScript.ScriptFullName)&"\config.txt",1)
Line 5,285:
config.Close
Set ofso = Nothing
</syntaxhighlight>
</lang>
 
{{Out}}
Line 5,299:
=={{header|Vedit macro language}}==
 
<langsyntaxhighlight lang="vedit">#11 = 0 // needspeeling = FALSE
#12 = 0 // seedsremoved = FALSE
Reg_Empty(21) // fullname
Line 5,333:
Message("fullname = ") Reg_Type(21) TN
Message("favouritefruit = ") Reg_Type(22) TN
Message("otherfamily = ") Reg_Type(23) TN</langsyntaxhighlight>
 
{{out}}
Line 5,346:
=={{header|Visual Basic}}==
 
<langsyntaxhighlight lang="vb">' Configuration file parser routines.
'
' (c) Copyright 1993 - 2011 Mark Hobley
Line 5,550:
Public Function btrim$(arg$)
btrim$ = LTrim$(RTrim$(arg$))
End Function</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 5,556:
{{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.
<langsyntaxhighlight lang="ecmascript">import "io" for File
import "/ioutil" for FileUtil
 
Line 5,609:
}
}
System.print(Configuration.new(configurationMap))</langsyntaxhighlight>
 
{{out}}
Line 5,621:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">a = open("rosetta_read.cfg")
 
while(not eof(#a))
Line 5,656:
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,678:
}
 
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,691:
</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>
10,327

edits