Search code examples
dctfe

Import content from filenames defined in an array


I can concatenate files read by import during compile time like this:

enum string a = import("a.txt");
enum string b = import("b.txt");
enum string result = a ~ b;

How can I get the concatenated result if I have the filenames in an array?

enum files = ["a.txt", "b.txt"];
string result;
foreach (f; files) {
  result ~= import(f);
}

This code returns with an error Error: variable f cannot be read at compile time.

Functional approach doesn't seem to work either:

enum files = ["a.txt", "b.txt"];
enum result = reduce!((a, b) => a ~ import(b))("", files);

It returns with the same error: Error: variable b cannot be read at compile time


Solution

  • I have found a solution that doesn't use string mixins:

    string getit(string[] a)() if (a.length > 0) {
        return import(a[0]) ~ getit!(a[1..$]);
    }
    
    string getit(string[] a)() if (a.length == 0) {
        return "";
    }
    
    enum files = ["a.txt", "b.txt"];
    enum result = getit!files;