Code Examples


The following sections contain a few examples of things you might want to do with Perl.

Sending Mail

You can get Perl to send email in several ways. One method that you see frequently is opening a pipe to the sendmail command and sending data to it (shown in Listing 27.5). Another method is using the Mail::Sendmail module (available through CPAN), which uses socket connections directly to send mail (as shown in Listing 27.6). The latter method is faster because it does not have to launch an external process. Note that sendmail must be running on your system for the Perl program in Listing 27.5 to work.

Listing 27.5. Sending Mail Using Sendmail

#!/usr/bin/perl open (MAIL, "| /usr/sbin/sendmail -t"); # Use -t to protect from users print MAIL <<EndMail; To: dpitts\@mk.net From: rbowen\@mk.net Subject: Email notification David,  Sending email from Perl is easy! Rich . EndMail close MAIL; 

Note

Note that the @ sign in the email addresses must be escaped so that Perl does not try to evaluate an array of that name. That is, dpitts@mk.net will cause a problem, so you need to use dpitts\@mk.net.

The syntax used to print the mail message is called a here document. The syntax is as follows:

print <<EndText; ..... EndText 


The EndText value must be identical at the beginning and at the end of the block, including any whitespace.


Listing 27.6. Sending Mail Using the Mail::Sendmail Module

#!/usr/bin/perl use Mail::Sendmail; %mail = ('To' => 'dpitts@mk.net',   'From' => 'rbowen@mk.net'   'Subject' => 'Email notification',   'Message' => 'Sending email from Perl is easy!', ); sendmail(%mail); 

Perl ignores the comma after the last element in the hash. It is convenient to leave it there; if you want to add items to the hash, you don't need to add the comma. This is purely a style decision.

Using Perl to Install a CPAN Module

You can use Perl to interactively download and install a Perl module from the CPAN archives by using the -M and -e commands. Start the process by using a Perl like this:

# perl -MCPAN -e shell


After you press Enter, you will see some introductory information and be asked to choose an initial automatic or manual configuration, which is required before any download or install takes place. Type no and press Enter to have Perl automatically configure for the download and install process; or, if desired, simply press Enter to manually configure for downloading and installation. If you use manual configuration, you must answer a series of questions regarding paths, caching, terminal settings, program locations, and so on. Settings are saved in a directory named .cpan in current directory. When finished, you will see the CPAN prompt:

cpan>


To have Perl examine your system and then download and install a large number of modules, use the install keyword, specify Bundle at the prompt, and then press Enter like this:

cpan> install Bundle::CPAN


To download a desired module (using the example in Listing 27.6), use the get keyword like so:

cpan> get Mail::Sendmail


The source for the module will be downloaded into the .cpan directory. You can then build and install the module using the install keyword, like this:

cpan> install Mail::Sendmail


The entire process of retrieving, building, and installing a module can also be accomplished at the command line by using Perl's -e option like this:

# perl -MCPAN -e "install Mail::Sendmail"



Note also that the @ sign did not need to be escaped within single quotation marks (''). Perl does not interpolate (evaluate variables) within single quotation marks, but does within double quotation marks and here strings (similar to << shell operations).

Purging Logs

Many programs maintain some variety of logs. Often, much of the information in the logs is redundant or just useless. The program shown in Listing 27.7 removes all lines from a file that contain a particular word or phrase, so lines that you know are not important can be purged. For example, you might want to remove all the lines in the Apache error log that originate with your test client machine because you know those error messages were produced during testing.

Listing 27.7. Purging Log Files

#!/usr/bin/perl # Be careful using this program! # This will remove all lines that contain a given word # Usage:  remove <word> <file> $word=@ARGV[0]; $file=@ARGV[1]; if ($file)  {   # Open file for reading   open (FILE, "$file") or die "Could not open file: $!";      @lines=<FILE>;   close FILE;   # Open file for writing   open (FILE, ">$file") or die "Could not open file for writing: $!";   for (@lines)  {     print FILE unless /$word/;   } # End for   close FILE; } else {   print "Usage: remove <word> <file>\n"; }  # End if...else 

The code uses a few idiomatic Perl expressions to keep it brief. It reads the file into an array using the <FILE> notation; it then writes the lines back out to the file unless they match the pattern given on the command line.

The die function kills program operation and displays an error message if the open statements fail. $! in the error message, as mentioned in the section on special variables, is the error message returned by the operating system. It will likely be something like 'file not found' or 'permission denied'.

Posting to Usenet

If some portion of your job requires periodic postings to Useneta FAQ listing, for examplethe following Perl program can automate the process for you. In the sample code, the posted text is read in from a text file, but your input can come from anywhere.

The program shown in Listing 27.8 uses the Net::NNTP module, which is a standard part of the Perl distribution. You can find more documentation on the Net::NNTP module by typing 'perldoc Net::NNTP' at the command line.

Listing 27.8. Posting an Article to Usenet

#!/usr/bin/perl # load the post data into @post open (POST, "post.file"); @post = <POST>; close POST; # import the NNTP module use Net::NNTP; $NNTPhost = 'news'; # attempt to connect to the remote host; # print an error message on failure $nntp = Net::NNTP->new($NNTPhost)   or die "Cannot contact $NNTPhost: $!"; # $nntp->debug(1); $nntp->post()   or die "Could not post article: $!"; # send the header of the post $nntp->datasend("Newsgroups: news.announce\n"); $nntp->datasend("Subject: FAQ - Frequently Asked Questions\n"); $nntp->datasend("From: ADMIN <root\@rcbowen.com>\n"); $nntp->datasend("\n\n"); # for each line in the @post array, send it for (@post)     {   $nntp->datasend($_); } # End for $nntp->quit; 

One-Liners

One medium in which Perl excels is the one-liner. Folks go to great lengths to reduce tasks to one line of Perl code. Perl has the rather undeserved reputation of being unreadable. The fact is that you can write unreadable code in any language. Perl allows for more than one way to do something, and this leads rather naturally to people trying to find the most arcane way to do things.

Named for Randal Schwartz, a Schwartzian Transform is a way of sorting an array by something that is not obvious. The sort function sorts arrays alphabetically; that is pretty obvious. What if you want to sort an array of strings alphabetically by the third word? Perhaps you want something more useful, such as sorting a list of files by file size? A Schwartzian Transform creates a new list that contains the information that you want to sort by, referencing the first list. You then sort the new list and use it to figure out the order that the first list should be in. Here's a simple example that sorts a list of strings by length:

@sorted_by_length =   map { $_ => [0] }            # Extract original list   sort { $a=>[1] <=> $b=>[1] } # Sort by the transformed value   map { [$_, length($_)] }     # Map to a list of element lengths   @list; 


Because each operator acts on the thing immediately to the right of it, it helps to read this from right to left (or bottom to top, the way it is written here).

The first thing that acts on the list is the map operator. It transforms the list into a hash in which the keys are the list elements and the values are the lengths of each element. This is where you put in your code that does the transformation by which you want to sort.

The next operator is the sort function, which sorts the list by the values.

Finally, the hash is transformed back into an array by extracting its keys. The array is now in the desired order.

Command-Line Processing

Perl is great at parsing the output of various programs. This is a task for which many people use tools such as awk and sed. Perl gives you a larger vocabulary for performing these tasks. The following example is very simple, but illustrates how you might use Perl to chop up some output and do something with it. In the example, Perl is used to list only those files that are larger than 10KB:

$ ls -la | perl -nae 'print "$F[8] is $F[4]\n" if $F[4] > 10000;' 


The -n switch indicates that I want the Perl code run for each line of the output. The -a switch automatically splits the output into the @F array. The -e switch indicates that the Perl code is going to follow on the command line.

Related Ubuntu and Linux Commands

You will use these commands and tools when using Perl with Linux:

a2p A filter used to translate awk scripts into Perl

find2perl A utility used to create Perl code from command lines using the find command

pcregrep A utility used to search data using Perl-compatible regular expressions

perlcc A compiler for Perl programs

perldoc A Perl utility used to read Perl documentation

s2p A filter used to translate sed scripts into Perl

vi The vi (actually vim) text editor




Ubuntu Unleashed
Ubuntu Unleashed 2011 Edition: Covering 10.10 and 11.04 (6th Edition)
ISBN: 0672333449
EAN: 2147483647
Year: 2006
Pages: 318

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net