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.

import strutils, os

proc main() =
  # Reading from stdin line by line
  for line in stdin.lines:
    # Convert the line to uppercase
    let ucl = line.toUpperAscii()
    
    # Write out the uppercased line
    echo ucl

  # Check for errors during reading
  if stdin.isAtEnd:
    if stdin.error != "":
      stderr.writeLine("error: ", stdin.error)
      quit(1)

# Call the main procedure
main()

In this Nim version:

  1. We import the strutils module for string manipulation and the os module for system operations.

  2. We define a main procedure that contains our program logic.

  3. We use a for loop with stdin.lines to read input line by line. This is similar to the scanner.Scan() in the original code.

  4. For each line, we use toUpperAscii() to convert it to uppercase.

  5. We print the uppercased line using echo.

  6. 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 with error.

  7. If there was an error, we print it to stderr and exit with a status code of 1.

  8. 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:

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

Then use the line filter to get uppercase lines:

$ cat /tmp/lines | nim c -r linefilter.nim
HELLO
FILTER

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.