Title here
Summary here
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/linesThen use the line filter to get uppercase lines.
$ cat /tmp/lines | rdmd line_filters.d
HELLO
FILTERIn this D version:
stdin.byLine() to create an input range that yields lines from standard input.foreach loop, which is idiomatic in D.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().writeln() to print each uppercased line.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.