April 07, 2005 Changing the size of an foreach() argument | ||||
---|---|---|---|---|
| ||||
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 |
April 07, 2005 Re: Changing the size of an foreach() argument | ||||
---|---|---|---|---|
| ||||
Posted in reply to AEon | > 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
Even 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;
}
}
}
|
Copyright © 1999-2021 by the D Language Foundation