Line Filters in D Programming Language

A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep and sed are common line filters.

Here’s an example line filter in D that writes a capitalized version of all input text. You can use this pattern to write your own D line filters.

import std.stdio;
import std.string;
import std.algorithm;

void main()
{
    // Wrapping stdin with a buffered reader gives us a convenient
    // readln method that reads a line at a time.
    auto stdin = stdin.byLine();

    // Iterate over each line from stdin
    foreach (line; stdin)
    {
        // Convert the line to uppercase
        string ucl = line.toUpper().idup;

        // Write out the uppercased line
        writeln(ucl);
    }

    // Check for errors during reading
    if (stdin.error)
    {
        stderr.writeln("error: ", stdin.error);
        import core.stdc.stdlib : exit;
        exit(1);
    }
}

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then use the line filter to get uppercase lines.

$ cat /tmp/lines | rdmd line_filters.d
HELLO
FILTER

In this D version:

  1. We use stdin.byLine() to create an input range that yields lines from standard input.
  2. We iterate over this range using a foreach loop, which is idiomatic in D.
  3. The toUpper() function is used to convert each line to uppercase. We use idup to create a mutable copy of the immutable string returned by toUpper().
  4. We use writeln() to print each uppercased line.
  5. After the loop, we check for any errors that occurred during reading.

Note that in D, we typically use rdmd to compile and run D scripts in one step, similar to how go run works in Go. The .d file extension is commonly used for D source files.