The basic Perl filter: What is it doing?

  1. The basic Perl filter
  2. Indentation

This is about as simple of a Perl script as you can get. While it doesn’t do much yet, this is a shell around which you can build quite a few useful scripts.

#!/usr/bin/perl

The first line is not Perl. The first line tells the operating system what language this script is written in. More specifically, it tells the operating system which program can interpret this script.

Most shell scripts use the pound character (“#”) for comments. What it really means is that every line that begins with a pound character is ignored by the scripting language. So Perl ignores this line because it begins with a pound character, but the operating system or shell that you’re using knows to send this script off to the program called /usr/bin/perl.

If your computer didn’t come with Perl pre-installed, you may have it installed in /usr/local/bin/perl instead. Nowadays, however, most operating systems come with Perl pre-installed.

while (<>) {
}

This is a while block. The part between the parentheses is an expression and the part between the two curly brackets gets acted on for as long as that expression does not return false, empty, zero, or, basically, as long as it returns something. We can put as much stuff as we want between those curly brackets. Perl will repeat them, or loop through them, for as long as that expression gives it something to work on.

The expression we have here is “<>”. This tells Perl that we want, line by line, everything in the files that we mentioned on the command line. If we don’t mention any files on the command line, Perl takes the standard input and gives that to us line by line instead.

For example, type:

./show

When you press return, you won’t get the command line back. Because we didn’t specify any filenames on the command line, Perl is waiting for the standard input. Because we didn’t give it any, it is waiting for us to type it. Type a few lines, pressing return after each line, and you’ll see the script echo whatever you type back.

Type Control-D to exit. Then type:

echo "Now is the time for all good muskrats to come to the aid of their country" | ./show

In Unix, the vertical bar is the pipe character. Whatever is on the left gets piped through to whatever is on the right. Echo echoes text to the screen normally, but in the above command the output from echo gets piped through to the show script.

Finally:

print;

This command is perhaps the most common one in Perl. You use it to output something, either to the screen or to a file.

What is it printing? Perl often makes assumptions about what you want. When we don’t give print anything to print, Perl assumes we want to print the current line from the while loop.

So what this script does is go through every line it gets and prints it out to the screen. If you’re familiar with Unix, we’ve just reinvented the cat command.

  1. The basic Perl filter
  2. Indentation