We're long overdue for a "D is awesome" post

Salih Dincer salihdb at hotmail.com
Wed May 31 00:28:40 UTC 2023


On Tuesday, 30 May 2023 at 21:42:04 UTC, H. S. Teoh wrote:
> ```d
> void genSplitHtml(Data data, ...) {
> 	auto outputTemplate = File("template.html", "r");
> 	foreach (...) {
> 		auto filename = generateFilename(...);
> 		auto sink = File(filename, "w").lockingTextWriter;
> 		...
> 		while (line; outputTemplate.byLine) {
> 			if (line.canFind("MAGIC_TOKEN")) {
> 				generateOutput(...);
> 			} else {
> 				sink.put(line);
> 			}
> 		}
> 	}
> }
>
> ```

I didn't know that `while` is used just like `foreach`. 0k4y, we 
can use `auto` in `while` condition or `if`, which lives in the 
same block as `auto`.

```d
while (line; outputTemplate.byLine) {...}
```

Does the following really work, thanks?


> ```d
> 	static struct MockFile {
> 		static string[string] files;
>
> 		string fname;
> 		this(string _fname, string mode) {
> 			// ignore `mode` for this test
> 			fname = _fname;
> 		}
>
> 		// Mock replacement for std.stdio.File.lockingTextWriter
> 		auto lockingTextWriter() {
> 			return (const(char)[] data) {
> 				// simulate writing to a file
> 				files[fname] ~= data.dup;
> 			};
> 		}
> 		void rewind() {} // dummy
> 		void close() {} // dummy
> 		auto byLine() {
> 			// We're mostly writing to files, and only
> 			// reading from a specific one. So just fake its
> 			// contents here.
> 			if (fname != "template.html") return [];
> 			else return [
> 				"<html>",
> 				"MAGIC_TOKEN",
> 				"</html>"
> 			];
> 		}
> 	}
> ```

SDB at 79


More information about the Digitalmars-d mailing list