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