X hits on this document

PDF document

Running and Debugging Perl - page 15 / 30

74 views

0 shares

0 downloads

0 comments

15 / 30

Running and Debugging Perl

How It Works To extract the relevant lines, we could write a program like this:

#!/usr/bin/perl use warnings; use strict;

open INPUT, "Mailbox" or die $!; while (<INPUT>) {

print if /^(Subject|From): /; }

However, that's a lot of work for a little job, and Perl was invented to make this sort of thing easy. Instead we use the -n flag to give us a while(<>) loop and -e to provide the remaining line. Perl internally translates our one-line incantation to this:

LINE: while (defined($_ = <ARGV>)) { print $_ if /^(Subject|From): /;

}

As you may suspect, we're not confined to just printing text with these one-liners. Indeed, we can use this to modify parts of a file. Let's say we had an old letter file newyear.txt containing this text:

Thank you for your custom throughout the previous year. We look forward to facing the challenges that 1999 will bring us, and hope that we will continue to serve you this year as well.

All our best wishes for a happy and prosperous 1999!

We could use perl to print an updated version of it as follows:

>perl -ne 's/1999/2000/g; print' newyear.txt Thank you for your custom throughout the previous year. We look forward to facing the challenges that 2000 will bring us, and hope that we will continue to serve you this year as well.

All our best wishes for a happy and prosperous 2000! >

Of course, we're only printing the changed version to STDOUT. We could go the next logical step and use redirection to save this output to a file instead, as we saw in Chapter 6.

>perl -ne 's/1999/2000/g; print' newyear.txt >changedfile.txt >

Since this is a pretty common operation – 'do something to the incoming data and print it out again' – perl lets use the -p flag instead of -n to automatically print out the line once we're finished. We can therefore save ourselves a valuable few keystrokes by saying this:

>perl -pe 's/1999/2000/g' newyear.txt

As you saw from the translation, these are ordinary loops, and we can use next and last on them as usual. To print out only those lines that don't start with a hash sign (#) we can say this:

293

Document info
Document views74
Page views74
Page last viewedSun Dec 04 19:37:19 UTC 2016
Pages30
Paragraphs723
Words10014

Comments