Line Filters in Perl
Our example demonstrates a line filter that reads input from stdin, processes it, and prints a derived result to stdout. This program writes a capitalized version of all input text. You can use this pattern to write your own Perl line filters.
In this Perl script:
We use a
while
loop to read from STDIN line by line. This is similar to the scanner in the original example.The
chomp
function removes the newline character from the end of each line.We use the
uc
function to convert each line to uppercase.We print each uppercase line to STDOUT.
After the loop, we check for any errors that might have occurred during reading. If there’s an error, we print it to STDERR and exit 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:
This Perl script provides the same functionality as the original example, reading input line by line, converting each line to uppercase, and printing the result.