Section 1.5.  A Whirlwind Tour of Perl

Table of Contents

1.5. A Whirlwind Tour of Perl

So, you want to see a real Perl program with some meat? (If you don't, just play along for now.) Here you are:

    @lines = `perldoc -u -f atan2`;
    foreach (@lines) {

Now, the first time you see Perl code like this, it can seem strange. (In fact, every time you see Perl code like this, it can seem strange.) But let's take it line by line, and see what this example does. (These explanations are brief; this is a whirlwind tour, after all. We'll see all of this program's features in more detail during the rest of this book. You're not really supposed to understand the whole thing until later.)

The first line is the #! line, as you saw before. You might need to change that line for your system, as we discussed earlier.

The second line runs an external command, named within backquotes ("` `"). (The backquote key is often found next to the number 1 on full-sized American keyboards. Be sure not to confuse the backquote with the single quote, "'".) The command we used is perldoc -u -f atan2; type that at your command line to see what its output looks like. The perldoc command is used on most systems to read and display the documentation for Perl and its associated extensions and utilities, so it should normally be available.[*] This command tells you something about the trigonometric function atan2; we're using it here as an example of an external command whose output we wish to process.

[*] If perldoc is unavailable, that probably means that your system doesn't have a command-line interface, and your Perl can't run commands (like perldoc) in backticks or via the piped-open, which you'll see in Chapter 14. In that case, you should skip the exercises that use perldoc.

The output of that command in the backticks is saved in an array variable called @lines. The next line of code starts a loop that processes each one of those lines. Inside the loop, the statements are indented. Though Perl doesn't require this, good programmers do.

The first line inside the loop body is the scariest one; it says s/\w<([^>]+)>/\U$1/g;. Without going into too much detail, we'll just say that this can change any line that has a special marker made with angle brackets (< >), and there should be at least one of those in the output of the perldoc command.

The next line, in a surprise move, prints out each (possibly modified) line. The resulting output should be similar to what perldoc -u -f atan2 would do on its own, but there will be a change where any of those markers appears.

Thus, in the span of a few lines, we've run another program, saved its output in memory, updated the memory items, and printed them out. This kind of program is a fairly common use of Perl, where one type of data is converted to another.

    Table of Contents
    © 2000- NIV