1package DirHandle; 2 3our $VERSION = '1.04'; 4 5=head1 NAME 6 7DirHandle - 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 22The C<DirHandle> method provide an alternative interface to the 23opendir(), closedir(), readdir(), and rewinddir() functions. 24 25The only objective benefit to using C<DirHandle> is that it avoids 26namespace pollution by creating globs to hold directory handles. 27 28=cut 29 30require 5.000; 31use Carp; 32use Symbol; 33 34sub 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 45sub 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 54sub open { 55 @_ == 2 or croak 'usage: $dh->open(DIRNAME)'; 56 my ($dh, $dirname) = @_; 57 opendir($dh, $dirname); 58} 59 60sub close { 61 @_ == 1 or croak 'usage: $dh->close()'; 62 my ($dh) = @_; 63 closedir($dh); 64} 65 66sub read { 67 @_ == 1 or croak 'usage: $dh->read()'; 68 my ($dh) = @_; 69 readdir($dh); 70} 71 72sub rewind { 73 @_ == 1 or croak 'usage: $dh->rewind()'; 74 my ($dh) = @_; 75 rewinddir($dh); 76} 77 781; 79