RosettaCodeData/Task/Read-a-configuration-file/Liberty-BASIC/read-a-configuration-file.basic
2023-07-01 13:44:08 -04:00

69 lines
2.2 KiB
Text

dim confKeys$(100)
dim confValues$(100)
optionCount = ParseConfiguration("a.txt")
fullName$ = GetOption$( "FULLNAME", optionCount)
favouriteFruit$ = GetOption$( "FAVOURITEFRUIT", optionCount)
needsPeeling = HasOption("NEEDSPEELING", optionCount)
seedsRemoved = HasOption("SEEDSREMOVED", optionCount)
otherFamily$ = GetOption$( "OTHERFAMILY", optionCount) 'it's easier to keep the comma-separated list as a string
print "Full name: "; fullName$
print "likes: "; favouriteFruit$
print "needs peeling: "; needsPeeling
print "seeds removed: "; seedsRemoved
print "other family:"
otherFamily$ = GetOption$( "OTHERFAMILY", optionCount)
counter = 1
while word$(otherFamily$, counter, ",") <> ""
print counter; ". "; trim$(word$(otherFamily$, counter, ","))
counter = counter + 1
wend
end
'parses the configuration file, stores the uppercase keys in array confKeys$ and corresponding values in confValues$
'returns the number of key-value pairs found
function ParseConfiguration(fileName$)
count = 0
open fileName$ for input as #f
while not(eof(#f))
line input #f, s$
if not(Left$(s$,1) = "#" or Left$( s$,1) = ";" or trim$(s$) = "") then 'ignore empty and comment lines
s$ = trim$(s$)
key$ = ParseKey$(s$)
value$ = trim$(Mid$(s$,len(key$) + 1))
if Left$( value$,1) = "=" then value$ = trim$(Mid$(value$,2)) 'optional =
count = count + 1
confKeys$(count) = upper$(key$)
confValues$(count) = value$
end if
wend
close #f
ParseConfiguration = count
end function
function ParseKey$(s$)
'key is the first word in s$, delimited by whitespace or =
s$ = word$(s$, 1)
ParseKey$ = trim$(word$(s$, 1, "="))
end function
function GetOption$( key$, optionCount)
index = Find.confKeys( 1, optionCount, key$)
if index > 0 then GetOption$ =(confValues$(index))
end function
function HasOption(key$, optionCount)
HasOption = Find.confKeys( 1, optionCount, key$) > 0
end function
function Find.confKeys( Start, Finish, value$)
Find.confKeys = -1
for i = Start to Finish
if confKeys$(i) = value$ then Find.confKeys = i : exit for
next i
end function