digitalmars.D.learn - Changing the size of an foreach() argument
- AEon (24/24) Apr 07 2005 On writing a simple function that will expand command line wildcards
- Ben Hinkle (14/20) Apr 07 2005 Even with the .dup you are still changing the array inside of the foreac...
On writing a simple function that will expand command line wildcards (using std.recls, once I figure that out), I have come accross a situation where the list of command line arguments char[][] args as defined in main() must change: void expand_Wildcard( char[][] args ) { char[][] tArgs = args.dup; int found = 0; foreach(int i, char[] file; args ) { ... args.length = 2; // Error vs. foreach } etc } In the foreach loop I would check every args / "file" and check it for a wildcard. Now should "file" actually contain a *, the args.length would need change. To make this work, I would need to make a duplicate (not a reference) via: char[][] tArgs = args.dup; Question is, is this correct? IIRC tArgs would actually be a "reference" to args, meaning, should I change anything in tArgs, this would also change args? AEon
Apr 07 2005
To make this work, I would need to make a duplicate (not a reference) via: char[][] tArgs = args.dup; Question is, is this correct? IIRC tArgs would actually be a "reference" to args, meaning, should I change anything in tArgs, this would also change args? AEonEven with the .dup you are still changing the array inside of the foreach. I suggest building up the expanded array inside the foreach over args: void expand_Wildcard( char[][] args ) { char[][] expandedArgs; int found = 0; foreach(char[] file; args ) { if (needsExpansion(file)) { char[][] expandedArg = expand(file); expandedArgs ~= expandedArg; } else { expandedArgs ~= file; } } }
Apr 07 2005