O'Reilly logo

Computer Science & Perl Programming by Jon Orwant

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5. The Birth of a One-Liner

Art Ramos

In the old days, if you wrote a program to perform data manipulation on some file, there were standard operations that had to be implemented to access the file’s data. Your program would have to open the file, read each record and process it, decide what to do with the newly manipulated data, and close the file. Perl doesn’t let you avoid any of these steps, but by employing some of Perl’s unique features, you can express your programs much more concisely—and they’ll be faster, too.

In this article, we’ll take a simple task and show how familiarity with Perl idioms can reduce the size and complexity of the solution. Our task is to display the lines of a file that are neither comments nor blank. Here’s our first attempt:

 #!/usr/bin/perl -w # Obtain filename from the first argument. $file = $ARGV[0]; # Open the file -- if it can't be opened, terminate # and print an error message. open INFILE, $file or die "Cannot open $file: $!"; # For each record in the file, read it in and process it. while (defined($line = <INFILE>)) { # Grab the first one and two characters of each line. $firstchar = substr($line,0,1); $firsttwo = substr($line,0,2); # If the line does NOT begin with a #! (we want to see # any bang operators) but the first character does begin # with a # (we don't want to see any # comments), skip it. if ($firsttwo ne "#!" && $firstchar eq "#") { next } # Or, if the line consists of only a newline (i.e. it's # a blank line), skip it. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required