File Coverage

blib/lib/Fortune.pm
Criterion Covered Total %
statement 82 83 98.8
branch 22 36 61.1
condition 12 25 48.0
subroutine 12 12 100.0
pod 7 8 87.5
total 135 164 82.3


line stmt bran cond sub pod time code
1             #
2             # Fortune.pm
3             #
4             # interface to fortune cookie databases
5             #
6             # by Greg Ward, 1999/02/20
7             #
8             # $Id: Fortune.pm,v 1.4 2000/02/27 02:22:31 greg Exp $
9             #
10              
11             package Fortune;
12             require 5.004;
13              
14 2     2   1525 use strict;
  2         4  
  2         80  
15 2     2   10 use Carp;
  2         6  
  2         191  
16 2     2   2123 use IO::File;
  2         29188  
  2         3269  
17              
18              
19             $Fortune::VERSION = '0.2';
20              
21             =head1 NAME
22              
23             Fortune - read and write fortune (strfile) databases
24              
25             =head1 SYNOPSIS
26              
27             # input
28             $ffile = new Fortune ($base_filename);
29             $ffile->read_header ();
30             $num_fortunes = $ffile->num_fortunes ();
31             $fortune = $ffile->read_fortune ($num);
32             $fortune = $ffile->get_random_fortune ();
33              
34             # create header file from data file -- NOT IMPLEMENTED YET
35             $ffile = new Fortune ($base_filename);
36             $ffile->write_header ();
37              
38             # write to data file -- NOT IMPLEMENTED YET
39             $ffile = new Fortune (">>$base_filename");
40             $ffile->write_fortune ($fortune);
41              
42             =head1 DESCRIPTION
43              
44             The C program is a small but important part of the Unix
45             culture, and this module aims to provide support for its "fortune
46             cookie" databases to Perl programmers. For efficiency, all versions of
47             C rely on a binary header consisting mainly of offsets into the
48             fortune file proper. Modern versions of fortune keep this header in a
49             separate file, and this is the style adopted by the C module;
50             the older style of munging the header and data into one large "compiled"
51             file is not (currently) supported.
52              
53             Using the C module makes it trivial to write a simplified
54             version of the C program:
55              
56             # trivial 'fortune' progam
57             my $fortune_filename = $ARGV[0];
58             my $fortune_file = new Fortune ($fortune_filename);
59             $fortune_file->read_header ();
60             my $fortune = $fortune_file->get_random_fortune ();
61             print $fortune;
62              
63             This can be compressed considerably:
64              
65             print new Fortune ($ARGV[0])->read_header()->get_random_fortune();
66              
67             Of course, this doesn't provide all of C's interesting
68             features, such as parallel databases of offensive fortunes, selection of
69             long or short fortunes, dealing with multiple fortune files, etc. If
70             you want C, use it -- but if you just want a simple Perl
71             interface to its data files, the C module is for you.
72              
73             Currently, the C module does not support writing fortune
74             databases. If it did, writing a simplified C (the program that
75             processes a fortune database to create the header file) would also be
76             trivial:
77              
78             # trivial (and hypothetical) 'strfile' program
79             my $fortune_filename = @ARGV[0];
80             my $fortune_file = new Fortune ($fortune_filename);
81             $fortune_file->write_header ();
82              
83             Note that the header filename is assumed to be just the name of the main
84             fortune database, with C<".dat"> appended. You can supply an alternate
85             header filename to the constructor, C, if you wish.
86              
87             =head1 METHODS
88              
89             =head2 Initialization/cleanup
90              
91             =over 4
92              
93             =item new (FILE [, HEADER_FILE])
94              
95             Opens a fortune cookie database. FILE is the name of the data file to
96             open, and HEADER_FILE (if given) the name of the header file that
97             contains (or will contain) meta-data about the fortune database. If
98             HEADER_FILE is not given, it defaults to FILE with C<".dat"> appended.
99              
100             The data file is opened via C, which Cs if the file
101             cannot be opened. The header file is I opened, whether you supply
102             its filename or not -- after all, it might not exist yet. Rather, you
103             must explicitly call C or C as
104             appropriate.
105              
106             =cut
107              
108             sub new
109             {
110 2     2 1 86 my ($class, $filename, $header_filename) = @_;
111 2   33     18 $class = ref $class || $class;
112 2   33     25 my $self = bless {
113             filename => $filename,
114             header_filename => $header_filename || $filename . ".dat",
115             }, $class;
116 2         12 $self->open_file ();
117 2         14 return $self;
118             }
119              
120              
121             sub DESTROY
122             {
123 2     2   28 my $self = shift;
124 2         10 $self->close_file ();
125             }
126              
127              
128             =item open_file ()
129              
130             Opens the fortune file whose name was supplied to the constructor. Dies
131             on failure.
132              
133             =cut
134              
135             sub open_file
136             {
137 2     2 1 5 my $self = shift;
138              
139 2 50       30 my $file = new IO::File $self->{'filename'} or
140             die "unable to open $self->{'filename'}: $!\n";
141 2         243 $self->{'file'} = $file;
142             }
143              
144              
145             =item close_file ()
146              
147             Closes the fortune file if it's open; does nothing otherwise.
148              
149             =cut
150              
151             sub close_file
152             {
153 2     2 1 3 my $self = shift;
154 2 50       28 $self->{'file'}->close () if defined $self->{'file'};
155             }
156              
157             =back
158              
159             =head2 Header functions (read and write)
160              
161             =over 4
162              
163             =item read_header ()
164              
165             Reads the header file associated with this fortune database. The name
166             of the header file is determined by the constructor C: either it is
167             based on the name of the data file, or supplied by the caller.
168              
169             If the header file does not exist, this function calls C
170             automatically, which has the same effect as reading the header from a file.
171              
172             The header contains the following values, which are stored as attributes
173             of the C object:
174              
175             =over 4
176              
177             =item C
178              
179             version number
180              
181             =item C
182              
183             number of strings (fortunes) in the file
184              
185             =item C
186              
187             length of longest string in the file
188              
189             =item C
190              
191             length of shortest string in the file
192              
193             =item C
194              
195             bit field for flags (see strfile(1) man page)
196              
197             =item C
198              
199             character that delimits fortunes
200              
201             =back
202              
203             C is available via the C method; if you're
204             interested in the others, you'll have to go grubbing through the
205             C object, e.g.:
206              
207             $fortune_file = new Fortune ('fortunes');
208             $fortune_file->read_header ();
209             $delim = $fortune_file->{'delim'};
210              
211             C Cs if there are any problems reading the header file,
212             e.g. if it seems to be corrupt or truncated.
213              
214             C returns the current C object, to allow for
215             sneaky one-liners (see the examples above).
216              
217             =cut
218              
219             sub read_header
220             {
221 1     1 1 3 my ($self) = @_;
222              
223 1         3 my $filename = $self->{'header_filename'};
224 1 50 33     21 if (! -f $filename && -f $self->{'filename'})
225 0         0 { return $self->compute_header(); }
226            
227 1 50       7 my $hdr_file = new IO::File $filename or
228             die "couldn't open $filename: $!\n|";
229 1         74 binmode ($hdr_file);
230              
231             # from the strfile(1) man page:
232             # unsigned long str_version; /* version number */
233             # unsigned long str_numstr; /* # of strings in the file */
234             # unsigned long str_longlen; /* length of longest string */
235             # unsigned long str_shortlen; /* shortest string length */
236             # unsigned long str_flags; /* bit field for flags */
237             # char str_delim; /* delimiting character */
238             # that 'char' is padded out to a full word, so the header is 24 bytes
239              
240 1         5 my $header;
241 1 50       33 read ($hdr_file, $header, 24) == 24
242             or die "failed to read full header\n";
243 1         8 @{$self}{qw(version numstr max_length min_length flags delim)} =
  1         10  
244             unpack ("NNNNNaxxx", $header);
245              
246 1         4 my $expected_offsets = $self->{'numstr'} + 1;
247 1         3 my $amount_data = 4 * $expected_offsets;
248 1         3 my $data;
249 1 50       7 read ($hdr_file, $data, $amount_data) == $amount_data
250             or die "failed to read offsets for all fortunes\n";
251 1         4 my @offsets = unpack ("N*", $data);
252 1 50       6 die sprintf ("found %d offsets (expected %d)\n",
253             scalar @offsets, $expected_offsets)
254             unless @offsets == $expected_offsets;
255 1         3 $self->{'offsets'} = \@offsets;
256              
257 1         11 close ($hdr_file);
258 1         6 return $self;
259             } # read_header
260              
261              
262             =item compute_header ([DELIM])
263              
264             Reads the contents of the fortune file and computes the header
265             information that would normally be found in a header (F<.dat>) file.
266             This is useful if you maintain a file of fortunes by hand and do not
267             have the corresponding data file.
268              
269             An optional delimiter argument may be passed to this function; if
270             present, that delimiter will be used to separate entries in the fortune
271             file. If not provided, the existing C attribute of the Fortune
272             object will be used. If that is not defined, then a percent sign ("%")
273             will be used.
274              
275             =cut
276              
277             sub compute_header
278             {
279 1     1 1 3 my ($self, $delim) = @_;
280 1 50 0     4 $delim = $self->{'delim'} || '%'
281             unless defined $delim;
282              
283 1         7 local $/ = $delim . "\n"; # read whole fortunes
284 1         2 my $filename = $self->{'filename'};
285 1 50       7 my $file = new IO::File $filename
286             or die "couldn't open $filename: $!\n";
287 1         67 my @offsets = (0); # start with offset of first fortune
288 1         2 my $fortune = '';
289 1         2 my($min, $max);
290 1         27 while (defined ($fortune = <$file>))
291             {
292 6         11 chomp $fortune;
293 6         14 my $len = length $fortune;
294 6 100 66     42 if (!defined $min || $len < $min) { $min = $len }
  1 100 100     3  
295 4         7 elsif (!defined $max || $len > $max) { $max = $len }
296 6         29 push (@offsets, tell $file);
297             }
298 1         3 $self->{'version'} = 1;
299 1         2 $self->{'numstr'} = $#offsets;
300 1         3 $self->{'max_length'} = $max;
301 1         15 $self->{'min_length'} = $min;
302 1         4 $self->{'flags'} = 0;
303 1         3 $self->{'delim'} = $delim;
304 1         19 $self->{'offsets'} = \@offsets;
305             }
306              
307             =item num_fortunes ()
308              
309             Returns the number of fortunes found by C.
310              
311             =cut
312              
313             sub num_fortunes
314             {
315 2     2 1 4 my $self = shift;
316 2 50       7 croak "header not read" unless defined $self->{'numstr'};
317 2         14 return $self->{'numstr'};
318             }
319              
320              
321             =item write_header ([DELIM])
322              
323             is not yet implemented.
324              
325             =cut
326              
327             =back
328              
329             =head2 Fortune input
330              
331             =over 4
332              
333             =item get_fortune (NUM)
334              
335             Reads string number NUM from the open fortune file. NUM is zero-based,
336             ie. it must be between 0 and C (inclusive). Cs if
337             you haven't opened the file and read the header, or if NUM is out of range.
338             (Opening the file is pretty hard to screw up, since it's taken care of for
339             you by the constructor, but you have to read the header explicitly with
340             C.) Returns the text of the fortune as a (possibly)
341             multiline string.
342              
343             =cut
344              
345             sub read_fortune
346             {
347 18     18 0 28 my ($self, $num) = @_;
348              
349 18 50 33     100 croak "fortune file not open"
350             unless defined $self->{'file'} and defined fileno ($self->{'file'});
351 18 50       68 croak "header file not read"
352             unless defined $self->{'numstr'};
353 18 100 66     536 croak "invalid fortune number (max " . ($self->{'numstr'}-1) . ")"
354             unless $num < $self->{'numstr'} && $num >= 0;
355              
356 16         31 my $start = $self->{'offsets'}[$num];
357 16         25 my $end = $self->{'offsets'}[$num+1];
358 16         25 my $length = $end - $start;
359              
360             # decrement length 2 bytes for most fortunes (to drop trailing "%\n"),
361             # and none for the last one (keep trailing newline)
362 16   50     47 my $delimlength = length $self->{'delim'} || 1;
363 16 100       40 $length -= ($num == $self->{'numstr'}-1) ? 0 : ($delimlength+1);
364              
365 16         25 my $file = $self->{'file'};
366 16         17 my $fortune;
367 16         119 seek ($file, $start, 0);
368 16 50       151 read ($file, $fortune, $length) == $length
369             or die "unable to read entire fortune\n";
370 16         70 return $fortune;
371             } # get_fortune
372              
373              
374             =item get_random_fortune ()
375              
376             Picks a random fortune for you and reads it with C.
377              
378             =cut
379              
380             sub get_random_fortune
381             {
382 10     10 1 222 my ($self) = @_;
383              
384 10 50       29 croak "header file not read"
385             unless defined $self->{'numstr'};
386 10         108 my $num = int (rand $self->{'numstr'});
387 10         48 return $self->read_fortune ($num);
388             }
389              
390              
391             =back
392              
393             =head2 Fortune output
394              
395             =over 4
396              
397             =item write_fortune (FORTUNE)
398              
399             is not yet implemented.
400              
401             =back
402              
403             =cut
404              
405             1;
406              
407             =head1 AUTHOR AND COPYRIGHT
408              
409             Written by Greg Ward Egward@python.netE, 20 February 1999.
410              
411             Copyright (c) 1999-2000 Gregory P. Ward. All rights reserved. This is free
412             software; you can redistribute it and/or modify it under the same terms as
413             Perl itself.
414              
415             =head1 AVAILABILITY
416              
417             You can download the C module from my web page:
418              
419             http://starship.python.net/~gward/perl/
420              
421             and it can also be found on CPAN.
422              
423             If you are using an operating system lacking a sufficient sense of
424             humour to include C as part of its standard installation (most
425             commercial Unices seem to be so afflicted), the Linux world has a
426             solution: the C distribution. The latest version as of
427             this writing is C, and the README file says you can
428             find it at
429              
430             http://www.progsoc.uts.edu.au/~dbugger/hacks/hacks.html
431              
432             This is the C implementation on which the C module is
433             based.