Line Filters in Crystal
Our line filter program reads input from stdin, processes it, and then prints a derived result to stdout. In this case, we’ll create a program that capitalizes all input text. This pattern can be used to create your own line filters in Crystal.
# Import required modules
require "readline"
# Main program
while line = Readline.readline
# Convert the line to uppercase
uppercase_line = line.upcase
# Print the uppercased line
puts uppercase_line
end
# Check for errors during input
if (err = Readline.error)
STDERR.puts "error: #{err}"
exit(1)
end
In this Crystal version:
We use the
Readline
module to read input line by line.The
while
loop continues reading lines until there’s no more input.Each line is converted to uppercase using the
upcase
method.The uppercased line is then printed using
puts
.After the loop, we check for any errors that might have occurred during input.
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 | crystal line_filter.cr
HELLO
FILTER
This Crystal implementation provides the same functionality as the original Go program, reading input line by line, converting each line to uppercase, and printing the result.
Crystal’s standard library provides convenient methods for string manipulation and I/O operations, making it straightforward to implement this kind of text processing task.