Foreach Command and Variable Scope
Posted: 2019-12-29 10:04:47
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:
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!
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
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!