Line Filters in Nim
Here’s the translation of the Go line filter program to Nim, presented in Markdown format suitable for Hugo:
Our line filter program reads input from stdin, processes it, and then prints a derived result to stdout. This example writes a capitalized version of all input text. You can use this pattern to write your own Nim line filters.
In this Nim version:
We import the
strutils
module for string manipulation and theos
module for system operations.We define a
main
procedure that contains our program logic.We use a
for
loop withstdin.lines
to read input line by line. This is similar to thescanner.Scan()
in the original code.For each line, we use
toUpperAscii()
to convert it to uppercase.We print the uppercased line using
echo
.After the loop, we check for errors. In Nim, we can check if we’ve reached the end of the input with
isAtEnd
and if there was an error witherror
.If there was an error, we print it to stderr and exit with a status code of 1.
Finally, we call the
main
procedure to run our program.
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: In Nim, we compile and run the program in one step using nim c -r
. The -r
flag tells Nim to run the program after compilation.