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.

use strict;
use warnings;

# Perl doesn't need to explicitly import standard modules like 'stdin' or 'stdout'

# Read from STDIN line by line
while (my $line = <STDIN>) {
    chomp $line;  # Remove newline character
    
    # Convert the line to uppercase
    my $uppercase_line = uc $line;
    
    # Print the uppercase line
    print "$uppercase_line\n";
}

# Check for errors during reading
if ($!) {
    print STDERR "Error: $!\n";
    exit 1;
}

In this Perl script:

  1. We use a while loop to read from STDIN line by line. This is similar to the scanner in the original example.

  2. The chomp function removes the newline character from the end of each line.

  3. We use the uc function to convert each line to uppercase.

  4. We print each uppercase line to STDOUT.

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

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

Then use the line filter to get uppercase lines:

$ cat /tmp/lines | perl line_filter.pl
HELLO
FILTER

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.