< Day Day Up > |
For this example, you're going to create a module to present information about a file. All of the information presented by this module is readily available in Perl through a variety of interfaces. In this module you're going to create functions for retrieving this information with convenient function names . The module is presented in Listing 17.7. Listing 17.7. File Information Module1: #!/usr/bin/perl -w 2: 3: package TYPFileInfo; 4: use strict; 5: 6: use Exporter; 7: our @ISA=qw(Exporter); 8: our @EXPORT=qw(bytes lines name extension modified $FileInfoName); 9: 10: our $FileInfoName = ""; 11: 12: sub bytes { # Size of the file in bytes 13: return -s $FileInfoName; 14: } 15: sub lines { # Number of text lines in the file 16: my $count = 0; 17: open(FH, $FileInfoName) die "Can't open $FileInfoName: $!"; 18: while(<FH>) { 19: $count++; 20: } 21: close(FH); 22: return $count; 23: } 24: sub name { # Filename portion of the path 25: if ($FileInfoName =~ m/([\w\.]+)$/) { 26: return ; 27: } 28: return $FileInfoName; 29: } 30: sub extension {# Extension portion of the filename 31: if ($FileInfoName =~ m/\.(.*?)$/) { 32: return ; 33: } 34: return ""; 35: } 36: sub modified { # Last modified time, suitable for localtime() 37: my @stats = stat($FileInfoName); 38: return $stats[9]; # Modified time. 39: } 40: 41: 1;
The program in Listing 17.8 will use the module from Listing 17.7. Listing 17.8. Sample Usage of the File Information Module1: #!/usr/bin/perl -w 2: 3: use strict; 4: use TYPFileInfo; 5: 6: $FileInfoName = "/temp/message.txt"; 7: 8: print "\nFilename: " . name(); 9: print "\nExtension: " . extension(); 10: print "\nModified: " . localtime(modified()); 11: print "\nBytes: " . bytes(); 12: print "\nLines: " . lines();
For this example, I set $FileInfoName to the name of a file that contained a mail message. The results looked something like this: Filename:
|