How to read a string from a file with interpolation

Your intuition is right, regular string interpolation is processed inside Julia’s parser, so "a $b c" parses as Expr(:string, "a ", :b, " c"). This then gets transformed to Base.string("a ", b, " c") in lowering.
If you want to do string interpolation programmatically, you need to implement the parsing yourself, like in my answer above, but that only gives you the expression tree, not the final string. Usually, this is implemented inside macros, so a macro could simply return this expression tree (escaped with esc), and interpolation would happen inside the macro caller’s scope. You can of course also use eval, like I did above, but that will only work in global scope and will be quite slow, because everything is executed at runtime.

3 Likes