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.
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:
- We use
string:uppercase/1
to convert the line to uppercase. - 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.
Then use the line filter to get uppercase lines.
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.