Документация
HTML CSS PHP PERL другое

Section B.5.  Some Important Modules

 
Previous
Table of Contents
Next

B.5. Some Important Modules

We describe some of the most important features[*] of the most important modules[Section B.5.  Some Important Modules] in this section. The modules that we discuss here should be found on every machine that has Perl except where noted otherwise. You can get the latest ones from CPAN.

[*] We're including the most important features of each module. See the module's own documentation to learn more.

[Section B.5.  Some Important Modules] 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.

B.5.1. The CGI and CGI_Lite Modules

Many people use Perl to write programs that a web server will run, called CGI program s. The CGI module comes with Perl, and the CGI_Lite module is available separately from CPAN. We showed an example in Chapter 15, and you can read more in the section "The Common Gateway Interface (CGI)" later in this appendix.

B.5.2. The Cwd Module

Sometimes you need to know what the current working directory's name is. (You could use ., but maybe you need to save the name so 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;

B.5.3. The Fatal Module

If you get tired of writing "or die" after every invocation of open or chdir, then maybe the Fatal module is for you. 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 (code contained within a module you're using, for example), so don't use this to fix poorly written code. It's a timesaver 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

B.5.4. The File::Basename Module

We covered this module in Chapter 15. Its 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";
    }

B.5.5. The File::Copy Module

When you need to copy or move files, the File::Copy module is for you. (It's often tempting to 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': $!";

B.5.6. The File::Spec Module

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 15), but you don't have to know if the system your program is running on uses a forward slash or some other character to separate those. 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. 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': $!";

B.5.7. The Image::Size Module

When you have an image file, you may 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;

B.5.8. The Net::SMTP Module

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), you may use the Net::SMTP module to do the work.[*] This module, available from CPAN, is OO, 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:

[*] Yes, this means you are now able to use Perl to send spam. Please don't.

    use Net::SMTP;
     
    my $from = 'YOUR_ADDRESS_GOES_HERE';         # maybe fred@bedrock.edu
    my $site = 'YOUR_SITE_NAME_GOES_HERE';       # maybe bedrock.edu
    my $smtp_host = 'YOUR_SMTP_HOST_GOES_HERE';  # maybe mail or mailhost
    my $to = 'president@whitehouse.gov';
     
    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;

B.5.9. The POSIX Module

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 I/O 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";
    }

B.5.10. The Sys::Hostname Module

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";

B.5.11. The Text::Wrap Module

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; 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");

B.5.12. The Time::Local Module

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.[*] (In a scalar context, that gives a formatted string representing the time, which is more often what you'd want.) If you need to go in the other direction, you may use the timelocal function from the Time::Local module instead. The value of $mon and $year for January 2004 are not 1 and 2004 as you might expect, so read the documentation before you use this module. For example:

[*] The return value of localtime in a list context is different than you might expect. See the documentation.

    use Time::Local;
     
    my $time = timelocal($sec, $min, $hr, $day, $mon, $year);

    Previous
    Table of Contents
    Next
    © 2000- NIV