File: Fstream.pm

package info (click to toggle)
perl-byacc 2.0-10
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 716 kB
  • sloc: ansic: 7,136; yacc: 2,035; perl: 1,779; makefile: 206; sh: 9
file content (119 lines) | stat: -rw-r--r-- 2,124 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# $Id: Fstream.pm,v 1.1 2002/04/10 04:58:09 srz Exp $

package Fstream;

# ----------------------------------------------------------------------------

=head1 NAME

Fstream - a class to encapsulate a filehandle as a stream;

=head1 SYNOPSIS

    use Fstream;

=head1 DESCRIPTION

Fstream wraps a filehandle and provides methods that make it easier to
write a lexer.

=cut

# ----------------------------------------------------------------------------

=head2 Class Methods
=over 4

=item new($filehandle, $name)
Creates an Fstream object from $filehandle (a filehandle glob
reference). $name is a string which is stored for debugging purposes
and may be accessed with &name.

=back
=cut

sub new {
    my ($class, $fh, $name) = @_;
    my $stream = bless {}, $class;
    $stream->{fh} = $fh;
    $stream->{name} = $name;
    $stream->{lineno} = 1;
    $stream->{save} = undef;
    $stream->{saved} = 0;
    return $stream;
}

# ----------------------------------------------------------------------------

=head2 Object Methods
=over 4

=item getc
Returns the next character in the stream, or the empty string if the
stream has been exhausted.

=cut

sub getc {
    my ($stream) = @_;
    my $c;

    if ($stream->{saved}) {
	$stream->{saved} = 0;
	$c = $stream->{save};
	if ($c eq "\n") {
	    $stream->{lineno}++;
	}
	return $c;
    }
    elsif (($c = getc($stream->{fh})) eq '') {
	return '';
    }
    else {
	$stream->{save} = $c;
	if ($c eq "\n") {
	    $stream->{lineno}++;
	}
	return $c;
    }
}

=item ungetc
Pushes the last character read back onto the stream, where it will be
returned on the next call to getc. You may only push one character
back on the stream.

=cut

sub ungetc {
    my ($stream) = @_;

    $stream->{saved} = 1;
    if ($stream->{save} eq "\n") {
	$stream->{lineno}--;
    }
}

=item lineno
Returns the line-number of the stream (based on the number of newlines
seen).

=cut

sub lineno {
    my ($stream) = @_;
    return $stream->{lineno};
}

=item name
Returns the name that was given in the constructor.

=back
=cut

sub name {
    my ($stream) = @_;
    return $stream->{name};
}

1;