Question
· Mar 10, 2020

Reducing the end variable in a FOR loop once executed

Dear All,

I'm looping through a list with characters (Parenthesis, square brackets etc) and I wish to remove these from the list.

The for loop and IF logic are effectively removing these items from a list.

However the variable I use for the maximum number of loops carries on beyond the number of items of the list after removal.

In the output value for these I get the integer of the for loop instead of a  null for the empty list fields.

I can see in the documentation that the end variable is not editable once the loop is started.

I looked at quitting out of the loop if the list value returned is null, but this isn't working either.

Any ideas please.

Regards

Stuart

Discussion (12)4
Log in or sign up to continue

Excerpt of Code as Promised:

set list = "ABC~DEF~GHI~JKL~MNO~[~PQR~]"

set SegmentList = $LISTFROMSTRING(list,"~")
Set SegmentCount = $LISTLENGTH(SegmentList)
FOR i = 1:1:SegmentCount{
IF ($LISTGET(SegmentList,i,i)= "[") {
set $LIST(SegmentList,i,i)=""
set OptionalSegment = "Y" 
}
ELSEIF ($LISTGET(SegmentList,i,i)= "]") {
set $LIST(SegmentList,i,i)=""
}
ELSEIF ($LISTGET(SegmentList,i,i)= "") {
QUIT
}
Write !, "Current Segment: "_$LISTGET(SegmentList,i,i)
Set SegmentFields = $LISTFROMSTRING(object.SegmentSubStructure,"~")
Set SegFieldCount = $LISTLENGTH(SegmentFields)
Hi Stuart

And using CONTINUE command ?

set list = "ABC~DEF~GHI~JKL~MNO~[~PQR~]"
set SegmentList = $LISTFROMSTRING(list,"~")
set SegmentCount = $LISTLENGTH(SegmentList)
set OptionalSegment="N"
FOR = 1:1:SegmentCount{
  if $LISTGET(SegmentList,i)= "[" set OptionalSegment = "Y" continue
  if $LISTGET(SegmentList,i)= "]" set OptionaSegment="N" continue
  write !, "Current Segment: "_$LISTGET(SegmentList,i)," ",OptionalSegment
  ;set SegmentFields = $LISTFROMSTRING(object.SegmentSubStructure,"~")
  ;set SegFieldCount = $LISTLENGTH(SegmentFields)
}

Hi Stuart,

As others have said, it's best practice to build a new variable, rather than amending what you have (there's some fancy name for the rule, I think, or maybe just "functional programming").

Looking at the string, I assume it is HealthShare HL7 message format, so the contents are pretty limited. In which case maybe a shortcut could be used:

s out=$Replace($Replace(list,"~]",""),"~[","")

Here's another alternative:

w $ZSTRIP($ZSTRIP(list,"*","[]"),"=>P")

I admit it could go horribly wrong with multiple nesting (I don't remember all the possible formats), so needs some testing. 

Hope you're keeping well,

Mike