Line Filters in Erlang

Here’s the translation of the Go line filter program to Erlang, along with explanations:

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 Erlang that writes a capitalized version of all input text. You can use this pattern to write your own Erlang line filters.

-module(line_filter).
-export([main/0]).

main() ->
    process_lines().

process_lines() ->
    case io:get_line("") of
        eof -> ok;
        {error, Reason} -> 
            io:format(standard_error, "Error: ~p~n", [Reason]),
            halt(1);
        Line ->
            UppercaseLine = string:uppercase(Line),
            io:format("~s", [UppercaseLine]),
            process_lines()
    end.

In Erlang, we use the io:get_line/1 function to read input line by line. This function returns eof when it reaches the end of the input, allowing us to process the input until it’s exhausted.

We use a recursive function process_lines/0 to continually read and process lines. For each line:

  1. We use string:uppercase/1 to convert the line to uppercase.
  2. We print the uppercased line using io:format/2.

If an error occurs during reading, we print it to standard error and exit the program with a non-zero status code.

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 | escript line_filter.erl
HELLO
FILTER

Note that in Erlang, we typically save our code in a .erl file and run it using the escript command, which allows us to run Erlang scripts directly from the command line.

This Erlang version accomplishes the same task as the original program, reading lines from standard input, converting them to uppercase, and printing the result to standard output.