Search code examples
filedstring-interpolation

Proper way to parse a file and build output


I'm trying to learn D and I thought after doing the hello world stuff, I could try something I wanted to do in Java before, where it was a big pain because of the way the Regex API worked: A little template engine. So, I started with some simple code to read through a file, character by character:

import std.stdio, std.file, std.uni, std.array;

void main(string [] args) {

    File f = File("src/res/test.dtl", "r"); 

    bool escape = false;
    char [] result;
    Appender!(char[]) appender = appender(result);

    foreach(c; f.rawRead(new char[f.size])) {
        if(c == '\\') {
            escape = true;
            continue;
        }
        if(escape) {
            escape = false;
            // do something special
        }
        if(c == '@') {
            // start of scope
        }
        appender.put(c);
    }
    writeln(appender.data());
}

The contents of my file could be something like this:

 <h1>@{hello}</h1>

The goal is to replace the @{hello} part with some value passed to the engine.

So, I actually have two questions: 1. Is that a good way to process characters from file in D? I hacked this together after searching through all the imported modules and picking what sounded like it might do the job. 2. Sometimes, I would want to access more than one character (to improve checking for escape-sequences, find a whole scope, etc. Should I slice the array for that? Or are D's regex functions up to that challenge? So far, I only found matchFirst and matchAll methods, but I would like to match, replace and return to that position. How could that be done?


Solution

  • D standard library does not provide what you require. What you need is called "string interpolation", and here is a very nice implementation in D that you can use the way you describe: https://github.com/Abscissa/scriptlike/blob/4350eb745531720764861c82e0c4e689861bb17e/src/scriptlike/core.d#L139

    Here is a blog post about this library: https://p0nce.github.io/d-idioms/#String-interpolation-as-a-library