Commit | Line | Data |
c07a80fd |
1 | package DirHandle; |
2 | |
b75c8c73 |
3 | our $VERSION = '1.00'; |
4 | |
c07a80fd |
5 | =head1 NAME |
6 | |
7 | DirHandle - supply object methods for directory handles |
8 | |
9 | =head1 SYNOPSIS |
10 | |
11 | use DirHandle; |
12 | $d = new DirHandle "."; |
13 | if (defined $d) { |
14 | while (defined($_ = $d->read)) { something($_); } |
15 | $d->rewind; |
16 | while (defined($_ = $d->read)) { something_else($_); } |
17 | undef $d; |
18 | } |
19 | |
20 | =head1 DESCRIPTION |
21 | |
22 | The C<DirHandle> method provide an alternative interface to the |
23 | opendir(), closedir(), readdir(), and rewinddir() functions. |
24 | |
25 | The only objective benefit to using C<DirHandle> is that it avoids |
26 | namespace pollution by creating globs to hold directory handles. |
27 | |
28 | =cut |
29 | |
30 | require 5.000; |
31 | use Carp; |
32 | use Symbol; |
33 | |
34 | sub new { |
35 | @_ >= 1 && @_ <= 2 or croak 'usage: new DirHandle [DIRNAME]'; |
36 | my $class = shift; |
37 | my $dh = gensym; |
38 | if (@_) { |
39 | DirHandle::open($dh, $_[0]) |
40 | or return undef; |
41 | } |
42 | bless $dh, $class; |
43 | } |
44 | |
45 | sub DESTROY { |
46 | my ($dh) = @_; |
47 | closedir($dh); |
48 | } |
49 | |
50 | sub open { |
51 | @_ == 2 or croak 'usage: $dh->open(DIRNAME)'; |
52 | my ($dh, $dirname) = @_; |
53 | opendir($dh, $dirname); |
54 | } |
55 | |
56 | sub close { |
57 | @_ == 1 or croak 'usage: $dh->close()'; |
58 | my ($dh) = @_; |
59 | closedir($dh); |
60 | } |
61 | |
62 | sub read { |
63 | @_ == 1 or croak 'usage: $dh->read()'; |
64 | my ($dh) = @_; |
65 | readdir($dh); |
66 | } |
67 | |
68 | sub rewind { |
69 | @_ == 1 or croak 'usage: $dh->rewind()'; |
70 | my ($dh) = @_; |
71 | rewinddir($dh); |
72 | } |
73 | |
74 | 1; |