This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
lib/_charnames.pm: Fix typo in comment
[perl5.git] / lib / DirHandle.pm
CommitLineData
c07a80fd 1package DirHandle;
2
5a77af9d 3our $VERSION = '1.05';
b75c8c73 4
c07a80fd 5=head1 NAME
6
c93f220f 7DirHandle - (obsolete) supply object methods for directory handles
c07a80fd 8
9=head1 SYNOPSIS
10
c93f220f
AP
11 # recommended approach since Perl 5.6: do not use DirHandle
12 if (opendir my $d, '.') {
13 while (readdir $d) { something($_); }
14 rewind $d;
15 while (readdir $d) { something_else($_); }
16 }
17
18 # how you would use this module if you were going to
c07a80fd 19 use DirHandle;
c93f220f 20 if (my $d = DirHandle->new(".")) {
c07a80fd 21 while (defined($_ = $d->read)) { something($_); }
22 $d->rewind;
23 while (defined($_ = $d->read)) { something_else($_); }
c07a80fd 24 }
25
26=head1 DESCRIPTION
27
c93f220f
AP
28B<There is no reason to use this module nowadays.>
29
c07a80fd 30The C<DirHandle> method provide an alternative interface to the
31opendir(), closedir(), readdir(), and rewinddir() functions.
32
c93f220f
AP
33Up to Perl 5.5, opendir() could not autovivify a directory handle from
34C<undef>, so using a lexical handle required using a function from L<Symbol>
35to create an anonymous glob, which took a separate step.
36C<DirHandle> encapsulates this, which allowed cleaner code than opendir().
37Since Perl 5.6, opendir() alone has been all you need for lexical handles.
c07a80fd 38
39=cut
40
41require 5.000;
42use Carp;
43use Symbol;
44
45sub new {
2b393bf4 46 @_ >= 1 && @_ <= 2 or croak 'usage: DirHandle->new( [DIRNAME] )';
c07a80fd 47 my $class = shift;
48 my $dh = gensym;
49 if (@_) {
50 DirHandle::open($dh, $_[0])
51 or return undef;
52 }
53 bless $dh, $class;
54}
55
56sub DESTROY {
57 my ($dh) = @_;
28ee7c39
SP
58 # Don't warn about already being closed as it may have been closed
59 # correctly, or maybe never opened at all.
04636146 60 local($., $@, $!, $^E, $?);
28ee7c39 61 no warnings 'io';
c07a80fd 62 closedir($dh);
63}
64
65sub open {
66 @_ == 2 or croak 'usage: $dh->open(DIRNAME)';
67 my ($dh, $dirname) = @_;
68 opendir($dh, $dirname);
69}
70
71sub close {
72 @_ == 1 or croak 'usage: $dh->close()';
73 my ($dh) = @_;
74 closedir($dh);
75}
76
77sub read {
78 @_ == 1 or croak 'usage: $dh->read()';
79 my ($dh) = @_;
80 readdir($dh);
81}
82
83sub rewind {
84 @_ == 1 or croak 'usage: $dh->rewind()';
85 my ($dh) = @_;
86 rewinddir($dh);
87}
88
891;