We describe some of the most important features[403] of the most important modules[404] in this section. These modules that we discuss here should generally be found on every machine that has Perl, except where mentioned. You can always get the latest ones from CPAN.
[403]We're including here merely the most important features of each module; see the module's own documentation to learn more.
[404]To be sure, there are other important modules whose use is too complex for most readers of this book, typically because using the module requires understanding Perl's references or objects.
Many people use Perl to write programs that a web server will run, generally called CGI programs. The CGI module comes with Perl, while the CGI_Lite module is available separately from CPAN. See Section B.16, "The Common Gateway Interface (CGI)" later in this appendix.
Sometimes you need to know what the current working directory's name is. (Well, you could often use ".", but maybe you need to save the name so that you can change back to this directory later.) The Cwd module, which comes with Perl, provides the cwd function, which you can use to determine the current working directory.
use Cwd; my $directory = cwd;
If you get tired of writing "or die" after every invocation of open or chdir, then maybe the Fatal module is for you. Just tell it which functions to work with, and those will be automatically checked for failure, as if you'd written "or die" and a suitable message after each one. This won't affect such calls in someone else's package (that is, code contained within a module you're using, for example), so don't use this to fix up poorly written code. It's just a timesaver, mostly for simple programs in which you don't need direct control over the error message itself. For example:
use Fatal qw/ open chdir /; chdir '/home/merlyn'; # "or die" is now supplied automatically
We covered this module in Chapter 13, "Manipulating Files and Directories". It's primary uses are to portably pull the basename or directory name from a full filename:
use File::Basename; for (@ARGV) { my $basename = basename $_; my $dirname = dirname $_; print "That's file $basename in directory $dirname.\n"; }
When you need to copy or move files, the File::Copy module is for you. (It's often tempting to simply call a system program to do these things, but that's not portable.) This module provides the functions move and copy, which may be used much as the corresponding system programs would be used:
use File::Copy; copy("source", "destination") or die "Can't copy 'source' to 'destination': $!";
When you need to manipulate a filename (more formally called a "file specification"), it's generally more portable and reliable to use the File::Spec module than to do the work yourself from Perl. For example, you can use the catfile function to put together a directory name and a filename to produce a long filename (as we saw in Chapter 13, "Manipulating Files and Directories"), but you don't have to know whether the system your program is running on uses a forward slash or some other character to separate those. Or you could use the curdir function to get the name of the current directory (".", on Unix systems).
The File::Spec module is object-oriented, but you don't need to understand objects to use it. Just call each function ("method", really) by using File::Spec and a small arrow before the function's name, like this:
use File::Spec; my $current_directory = File::Spec->curdir; opendir DOT, $current_directory or die "Can't open current directory '$current_directory': $!";
When you have an image file, you'll often want to know what its height and width are. (This is handy for making programs that write HTML, if you wish for an IMG tag to indicate the image's dimensions.) The Image::Size module, which is available from CPAN, understands the common GIF, JFIF (JPEG), and PNG image types, and some others. For example:
use Image::Size; # Get the size of fred.png my($fred_height, $fred_width) = imgsize("fred.png"); die "Couldn't get the size of the image" unless defined $fred_height;
If you want your program to be able to send email through an SMTP server (which is the way most of us send email these days, whether you knew that or not), you may use the Net::SMTP module to do the work.[405] This module, which is available from CPAN, is object-oriented, but you may simply follow the syntax to use it. You will need to change the name of your SMTP host and the other items to make this work on your system. Your system administrator or local expert can tell you what to use. For example:
[405]Yes, this means that you are now able to use Perl to send spam. Please don't.
use Net::SMTP; my $from = 'YOUR_ADDRESS_GOES_HERE'; # maybe [email protected] my $site = 'YOUR_SITE_NAME_GOES_HERE'; # maybe bedrock.edu my $smtp_host = 'YOUR_SMTP_HOST_GOES_HERE'; # maybe mail or mailhost my $to = '[email protected]'; my $smtp = Net::SMTP->new($smtp_host, Hello => $site); $smtp->mail($from); $smtp->to($to); $smtp->data( ); $smtp->datasend("To: $to\n"); $smtp->datasend("Subject: A message from my Perl program.\n"); $smtp->datasend("\n"); $smtp->datasend("This is just to let you know,\n"); $smtp->datasend("I don't care what those other people say about you,\n"); $smtp->datasend("I still think you're doing a great job.\n"); $smtp->datasend("\n"); $smtp->datasend("Have you considered enacting a law naming Perl \n"); $smtp->datasend("the national programming language?\n"); $smtp->dataend( ); # Not datasend! $smtp->quit;
If you need access to the POSIX (IEEE Std 1003.1) functions, the POSIX module is for you. It provides many functions that C programmers may be used to, such as trigonometric functions (asin, cosh), general mathematical functions (floor, frexp), character-identification functions (isupper, isalpha), low-level IO functions (creat, open), and some others (asctime, clock). You'll probably want to call each of these with its "full" name; that is, with POSIX and a pair of colons as a prefix to the function's name:
use POSIX; print "Please enter a number: "; chomp(my $str = <STDIN>); $! = 0; # Clear out the error indicator my($num, $leftover) = POSIX::strtod($str); if ($str eq '') { print "That string was empty!\n"; } elsif ($leftover) { my $remainder = substr $str, -$leftover; print "The string '$remainder' was left after the number $num.\n"; } elsif ($!) { print "The conversion function complained: $!\n"; } else { print "The seemingly-valid number was $num.\n"; }
The Sys::Hostname module provides the hostname function, which will be the network name of your machine, if that can be determined. (If it can't be determined, perhaps because your machine is not on the Internet or not properly configured, the function will die automatically; there's no point in using or die here.) For example:
use Sys::Hostname; my $host = hostname; print "This machine is known as '$host'.\n";
The Text::Wrap module supplies the wrap function, which lets you implement simple word-wrapping. The first two parameters specify the indentation of the first line and the others, respectively; the remaining parameters make up the paragraph's text:
use Text::Wrap; my $message = "This is some sample text which may be longer " . "than the width of your output device, so it needs to " . "be wrapped to fit properly as a paragraph. "; $message x= 5; print wrap("\t", "", "$message\n");
If you have a time (for example, from the time function) that needs to be converted to a list of year, month, day, hour, minute, and second values, you can do that with Perl's built-in localtime function in a list context.[406] (In a scalar context, that gives a nicely formatted string representing the time, which is more often what you'd want.) But if you need to go in the other direction, you may use the timelocal function from the Time::Local module instead. It's important to note that the value of $mon and $year for January 2004 are not 1 and 2004 as you might expect, so be sure to read the documentation before you use this module. For example:
[406]The actual return value of localtime in a list context is a little different than you might expect; see the documentation.
use Time::Local; my $time = timelocal($sec, $min, $hr, $day, $mon, $year);
Copyright © 2002 O'Reilly & Associates. All rights reserved.