dir is open

G

George Mpouras

how do I know if a directory is open so not have warnings when closedir
it ? At files there is the fileno.
 
J

Jürgen Exner

George Mpouras said:
how do I know if a directory is open so not have warnings when closedir
it ? At files there is the fileno.

By checking the return value of opendir()?

jue
 
$

$Bill

how do I know if a directory is open so not have warnings when closedir it ? At files there is the fileno.

Something to this effect should work:

my $dh;
opendir $dh, $_ or do { warn "open $_ failed: $! ($^E)\n"; undef $dh; };

....
readdir $dh, ...
....


closedir $dh if $defined $dh;
 
G

George Mpouras

Στις 2/11/2013 7:37 πμ, ο/η $Bill έγÏαψε:
y $dh;
opendir $dh, $_ or do { warn "open $_ failed: $! ($^E)\n"; undef $dh; };

...
readdir $dh, ...
...


closedir $dh if $defined $dh;




this is a very good idea.

I wonder where is this Perl mystic cryptic where the handles are kept.
fileno knows it , but dirhandles are not there , but there must be also
one for the dirhandles
 
R

Rainer Weikusat

George Mpouras said:
Στις 2/11/2013 7:37 πμ, ο/η $Bill έγÏαψε:




this is a very good idea.

To a degree: perl knows if the directory handle is open and will close
it automatically when the corresponding object is destroyed. This means
this will work:

my $dh;
opendir($dh, '/tmp') if rand(10) > 5;
$dh = undef;

or this

{
my $dh;
# do something which might open a dir handle
}
# will be closed here if it was opened
 
$

$Bill

To a degree: perl knows if the directory handle is open and will close
it automatically when the corresponding object is destroyed. This means
this will work:

my $dh;
opendir($dh, '/tmp') if rand(10) > 5;
$dh = undef;

But obviously, you can't do the undef until after the readdir/closedir
is done or you get no dir entries.
 
C

Charles DeRykus

Στις 2/11/2013 7:37 πμ, ο/η $Bill έγÏαψε:

this is a very good idea.

I wonder where is this Perl mystic cryptic where the handles are kept.
fileno knows it , but dirhandles are not there , but there must be also
one for the dirhandles

Yes, see Ben's response.

So perhaps another slightly "better" hack:

closedir $dh if ref $dh eq 'GLOB';
 
C

Charles DeRykus

I don't think this helps, does it? You still need eval if you want to
pass in arbitrary scalars.

Indeed, it looked like "eval" was being thoroughly ignored for a
"defined $dh" so I suggested the slight improvement.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top