Line Filters in Pascal

Here’s the translation of the Go line filter program to Pascal, formatted in Markdown for Hugo:

program LineFilter;

uses
  SysUtils;

var
  line: string;

begin
  // Read input lines until EOF
  while not Eof do
  begin
    // Read a line from standard input
    ReadLn(line);
    
    // Convert the line to uppercase
    line := UpperCase(line);
    
    // Write out the uppercased line
    WriteLn(line);
  end;

  // Check for errors during read
  if IOResult <> 0 then
  begin
    WriteLn(ErrOutput, 'Error: ', IOResult);
    Halt(1);
  end;
end.

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

In this program:

  1. We use a while loop to read lines from standard input until we reach the end of the file (EOF).

  2. For each line, we use the ReadLn function to read a line from standard input.

  3. We then use the UpperCase function to convert the line to uppercase.

  4. The uppercased line is written to standard output using WriteLn.

  5. After the loop, we check for any I/O errors using IOResult. If an error occurred, we print an error message 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 | ./linefilter
HELLO
FILTER

Note that in Pascal, we don’t have a built-in buffered scanner like in some other languages. Instead, we’re using the standard input/output functions provided by the language. This approach is simpler but might be less efficient for very large inputs. For more advanced usage, you might want to consider using file handling units like TextFile for buffered I/O.