JPRED-2 copy the portable branch into Git
[jpred.git] / jpred / lib / Read.pm
1 package Read;
2
3 use strict;
4 use warnings;
5 use Carp;
6
7 use base qw(Common);
8
9 use IO::String;
10 use File::Temp;
11
12 =head1 NAME
13
14 Read - Two base methods for reading information.
15
16 =head1 DESCRIPTION
17
18 This module contains three methods for reading information into a program. They allow the reading of information from a string or filename and expect the method read() to be defind by the class that inherits this module.
19
20 =head1 METHODS
21
22 =head2 read_file($path)
23
24 Opens a file at the given path and then calls the read method.
25
26 =head2 read_file_gzip($path)
27
28 Calls read_file after decompressing a gzip compressed file using the system gzip command.
29
30 =head2 path($path)
31
32 Accessor for finding where a file was located.
33
34 =head2 read_string($scalar)
35
36 Reads the data in the scalar and passes it to the read method.
37
38 =head2 read($filehandle)
39
40 This method will cause a fatal error unless it's overidden by the class that inherits this module.
41
42 =cut
43
44 sub read {
45   confess "The inheriting package hasn't defined the read() method\n";
46 }
47
48 sub read_file {
49   my ( $self, $fn ) = @_;
50
51   open my $fh, $fn or confess "Can't open file $fn: $!";
52   $self->path($fn);
53   $self->read($fh);
54 }
55
56 =head2 read_gzip_file($scalar);
57
58 Like read_file($scalar), but ungzip's the file first.
59
60 =cut
61
62 sub read_gzip_file {
63   my ( $self, $fn ) = @_;
64
65   my $gzipd_fn = File::Temp->new->filename;
66
67   system("gzip -dc $fn > $gzipd_fn");
68
69   $self->read_file($gzipd_fn);
70 }
71
72 sub read_string {
73   my ( $self, $string ) = @_;
74
75   my $fh = IO::String->new($string);
76   $self->read($fh);
77 }
78
79 1;