This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Setting $_ to multiline glob in @INC filter
[perl5.git] / lib / DirHandle.pm
1 package DirHandle;
2
3 our $VERSION = '1.04';
4
5 =head1 NAME 
6
7 DirHandle - supply object methods for directory handles
8
9 =head1 SYNOPSIS
10
11     use DirHandle;
12     $d = DirHandle->new(".");
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: DirHandle->new( [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     # Don't warn about already being closed as it may have been closed 
48     # correctly, or maybe never opened at all.
49     local($., $@, $!, $^E, $?);
50     no warnings 'io';
51     closedir($dh);
52 }
53
54 sub open {
55     @_ == 2 or croak 'usage: $dh->open(DIRNAME)';
56     my ($dh, $dirname) = @_;
57     opendir($dh, $dirname);
58 }
59
60 sub close {
61     @_ == 1 or croak 'usage: $dh->close()';
62     my ($dh) = @_;
63     closedir($dh);
64 }
65
66 sub read {
67     @_ == 1 or croak 'usage: $dh->read()';
68     my ($dh) = @_;
69     readdir($dh);
70 }
71
72 sub rewind {
73     @_ == 1 or croak 'usage: $dh->rewind()';
74     my ($dh) = @_;
75     rewinddir($dh);
76 }
77
78 1;