Foreach Command and Variable Scope

Get help using and writing Nisus Writer Pro macros.
Post Reply
waltzmn
Posts: 43
Joined: 2013-05-05 12:52:00

Foreach Command and Variable Scope

Post by waltzmn »

Hello again, kind people. Apologies again for being apparently the only user asking questions here. At least I'm giving you something to read -- and I'm definitely learning things!

I'm still working on this CSV macro, and am having a problem, I think, with variable scope. What I need to do is take any field that contains a comma and put quotes around it. The fields are in an array called, un-originally, $TheFields.

So I tried to use this code to go through the fields, find any containing a comma, and put quotes around it. The code I used is this:

Code: Select all

	foreach $OneField in $TheFields
		If $OneField.find(',')
			#	There's a comma in there; put quotes around the field
			$OneField = '"' & $OneField & '"'	# Put quote marks " around the field
			Prompt $OneField
		End	# If $OneField.find(',')
	End # foreach $OneField in $TheFields
The prompt command shows that this works within the foreach loop. If $OneField has the value, say, Help, please, then the Prompt command will show "Help, please".

But when I exit the loop, $TheFields is unchanged. No quotation marks.

I'm pretty sure I know what is happening; $OneField is local to the foreach loop, and it doesn't affect the source array. So when I exit the foreach loop, the changes are gone. But is there a way to make changes to $TheFields? Or do I have to do this some other way?

Thanks!

User avatar
phspaelti
Posts: 1069
Joined: 2007-02-07 00:58:12
Location: Japan

Re: Foreach Command and Variable Scope

Post by phspaelti »

You've got that exactly right. The iterator variable of the foreach loop is a local copy. So changing it does not persist beyond the loop. One way to achieve what you want is to use the index to access the original. Note that the foreach loop has a variant that allows you to get the index of the current value:

Code: Select all

foreach $i, $value in $values
    $values[$i] = …
end
philip

waltzmn
Posts: 43
Joined: 2013-05-05 12:52:00

Re: Foreach Command and Variable Scope

Post by waltzmn »

phspaelti wrote:
Note that the foreach loop has a variant that allows you to get the index of the current value:

Code: Select all

foreach $i, $value in $values
    $values[$i] = …
end
That did it! Thank you again.

At this point, pending field testing, the macro seems to be done, so maybe you'll be through with me for a while.

Post Reply