'pp' for D?

linkrope linkrope at github.com
Mon Sep 30 14:24:27 PDT 2013


On Monday, 30 September 2013 at 04:20:32 UTC, Ali Çehreli wrote:
> I don't know a Phobos function either but the following should 
> work:
>
> import std.stdio;
> import std.traits;
>
> void pp(T)(File output, T value)
> {
>     static if (isSomeString!T) {
>         output.writef(`"%s"`, value);
>
>     } else {
>         output.write(value);
>     }
> }
>
> void pp(T)(T value)
> {
>     pp(stdout, value);
> }
>
> void main()
> {
>     pp("hello");
>     pp(42);
> }
>
> Ali

OK.

But putting quotes around a string value is obviously not enough.
What if the string contains a quote? "hell\"o" would become 
`"hell"o"`!

Seems, I have the choice between:

string repr(T)(T value)
{
     auto writer = appender!string();
     auto fmt = FormatSpec!char("%s");

     formatElement(writer, value, fmt);
     return writer.data;
}

(relying on the "undocumented" formatElement),
or the aforementioned array detour:

string repr(T)(T value)
{
     return "%(%s%)".format([value]);
}


More information about the Digitalmars-d-learn mailing list