X hits on this document

PDF document

Running and Debugging Perl - page 14 / 30

81 views

0 shares

0 downloads

0 comments

14 / 30

Chapter 9

This technique is most commonly used for two purposes:

To construct quick programs in conjunction with some of the other switches we'll see below To test out little code snippets and check how Perl works.

For example, if I wasn't sure whether an underscore would be matched by \w in a regular expression, I'd write something like this to check:

  • >

    perl -e 'print qq/Yes, it's included\n/ if q/_/ =~ /\w/;'

Yes, it's included >

It's often quicker to do this than to go hunting through books and online documentation trying to look it up. As Larry Wall says, 'Perl programming is an empirical science'. You learn by doing it. If you're not sure about some element of Perl, get to a command line and try it out!

  • -

    n and -p

As mentioned above, you can combine -e with other switches to make useful programs on the command line. The most common switches used in this way are -n and -p. These are both concerned with reading <ARGV>. In fact, -n is equivalent to this:

while (<>) { "..your code here.." }

We can use this to produce programs for scanning through files, searching for matching lines, changing text, and so on. For example, here's a one-liner to print out the subject of any new items of mail I have, along with whom the mail is from:

Try It Out : New Mail Check

All the incoming mail arrives in a file called Mailbox on my computer. Each piece of mail contains a header, which contains information about it. For instance, here's part of the header from an email I sent to perl5-porters:

Date: Mon, 3 Apr 2000 14:22:03 +0900 From: Simon Cozens <simon@cozens.net> To: perl5-porters@perl.org Subject: [PATCH] t/lib/b.t Message-ID: <20000403142203.A1437@SCOZENS> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Mailer: Mutt 1.0.1i

As you can see, each header line consists of some text, then a colon and a space, then some more text. If we extract the lines that start Subject: and From:, we can summarize the contents of the mailbox.

Here's how to do it on the command line:

>perl -ne 'print if /^(Subject|From): /' Mailbox From: Simon Cozens <simon@brecon.co.uk> Subject: [PATCH] t/lib/b.t >

292

Document info
Document views81
Page views81
Page last viewedWed Dec 07 16:25:14 UTC 2016
Pages30
Paragraphs723
Words10014

Comments