How to handle null values within a list
Hi All I am a beginner and I am learning Objectscript and I would appreciate a steer regarding a problem I am solving.
The issue I have spent some time on resolving without success is that I have the stream listed below and as you can see it has some gaps in it.
Stream
das
is
wp
dsa
nmkHere is the import method
IF ##class(%File).Exists(dir) '=1 {
write !, "Unable to Open: "_dir
QUIT
} ELSE {
write "File: "_dir_" is open"
}
// instantiate a new class called file
set file = ##class(%Stream.FileCharacter).%New()
// create a new variable called sc
set sc = file.LinkToFile(dir)
set count=1
WHILE ('file.AtEnd) {
set delim=" "
set line = file.ReadLine()
set i=1
write !, "Loop started"
write *32
if (line '="") {
write !, "Read started"
write *32
set ^answers(count)=$LISTFROMSTRING(line, delim)
write *32
set ^attempt(count)=^attempt(count)_$ZHEX(($ASCII($LIST(^answers(count)))))
write "Attempt:", ^attempt(count) ,!
set countdown=$LENGTH(line,delim)
set i=$INCREMENT(i)
set count=$INCREMENT(count)
}
}Reading from streams is sequential and I have been trying to find a way of using LISTFROMSTRING to read these values. The issue is that I have been having some trouble trying to account for the blank spaces and they stop the program from running in its tracks. I have tried using $EXTRACT and $PIECE and I want to be able to remove these null spaces when writing the lines out to the subscripted variable.
What would be the best way of reading in the values whilst bearing in mind that I don't want to have any blank spaces within any list I create?
BTW I am open to using globals, arrays or local variables
Thanks in advance and I really do appreciate any assistance on this.
Comments
If you want to get rid of spaces the simplest way is use $TRANSLATE
SET NoSpaces=$TRANSLATE(line," ")
Thanks
$ZSTRIP will delete repeating characters
set newstring=$ZSTRIP(oldstring,"=W") // for whitespace
set newstring=$ZSTRIP(oldstring,"="," ") // for only spaces
Thanks
What do you want your $list to look like?
If you want the end result to be like this:
$lb("das", "is", "wp", "dsa", "nmk")try this code (assumes dir is shorter that 3 641 144 chars):
ClassMethod test(dir = "test.txt")
{
set file = ##class(%Stream.FileCharacter).%New()
set file.LineTerminator = $c(1)
do file.LinkToFile(dir)
set str = file.Read($$$MaxStringLength)
kill file
set separator = $c(13,10)
do {
set newstr = str
set str = $replace(str, separator _ separator, separator)
} while newstr'=str
set:$e(str, 1, $l(separator))=separator str=$e(str, 1 + $l(separator), *)
set:$e(str, *-$l(separator)+1, *)=separator str=$e(str, 1, *-$l(separator))
set list = $lfs(str, separator)
quit list
}This is a naive implementation assuming you don't care about the speed.
Faster solution would go through file line by line.
Thanks