2

I know that we can parse a CSV line ( ';' separator ) with something like that :

delim = ';'
myline="i;want;to;know;what;love;is"
parse var myline w1 (delim) w2 (delim) w3 (delim) w4 (delim) w5 (delim) w6 (delim) w7
say w1 w2 w3 w4 w5 w6 w7

I want to know if there is a way to simplify the iteration of the 'w# (delim)'in order to do something like :

parse var myline w1 (delim) w2 (delim) ... (delim) w6 (delim) w7
/* then we will have all w1 to w7 defined

I could do a function with some array to do that but is it possible natively on rexx, i was just wondering

Thanks

user1117862
  • 121
  • 3
  • 9

1 Answers1

14

Sure, if what you really want is n variables named w1, w2, ... wn:

do i = 1 by 1 while myline <> ''
    parse var myline word (delim) myline
    interpret "w" || i "= word"
end

But the Rexx-y way to do this is using a "stem array":

delim = ';'
do i = 1 by 1 while myline <> ''
    parse var myline w.i (delim) myline
end
w.0 = i-1

or even:

do i = 1 by 1 while myline <> ''
    parse var myline w.i ';' myline
end
w.0 = i-1

When you're done, you have an array w. with it's count in w.0 and the n words in w.1, w.2, ... up through w.n. This is better because Rexx has special handling for the part following the .: you can use any variable, and its value will be used instead. So printing all those words is just:

do i = 1 to w.0
    say w.i
end

Or re-assembling them is just:

line = ""
do i = 1 to w.0
    line = line || w.i || ';'
end
Ross Patterson
  • 9,527
  • 33
  • 48
  • I didn't know that Parse was assigning the remaining words. Thanks, tha help me a lot. – user1117862 Mar 18 '13 at 18:31
  • I think you need a terminating condition for the DO loop. Try appending a delimiter to the end of `MYLINE` then `DO I = 1 BY 1 UNTIL STRIP(MYLINE) = ''` – NealB Mar 19 '13 at 21:04
  • @NealB Yeah, that'll teach me to type code without running it. Updated with `while myline <> ''`, that'll do the job. – Ross Patterson Mar 19 '13 at 21:38
  • the `do i = 1 by 1 while myline <> ''` is perfect as a loop (@NealB). The assign `w.0 = i` is wrong in my Rexx: `i` is incremented before the until is tested: so it would be `w.0 = i - 1` – Martin Jul 15 '15 at 20:04
  • @Martin Yeah, I typed that code, I didn't run it. Fixed now. – Ross Patterson Jul 18 '15 at 00:44
  • Many is the time I've wished Rexx allowed expressions as stem suffixes. Then I'd do something like: `do w.0 = 1 by 1 while myline <> '' parse var myline w.(w.0) ';' myline end` – Ross Patterson Mar 30 '18 at 01:41