The way I usually do that is to use a stack just like in the old PDP-11 days. This ensures that files are opened and closed in a non-abusive way so that you can catch the abuse at the right point and may even solve the problem before it happens, just because you organised your recursive code better.
By the way, the hash-style subroutine parameters can be replaced with whatever you normally do, they are only there for clarity although if you do want to try that out too... don't forget to enclose the parameter array (@_) in brackets when reloading it into a hash or it won't work -- the point at which you can check the number of open files is marked in subroutine "Open"
my %controlCentre=(); $controlCentre{ FH } = []; $controlCentre{ DH } = []; Traverse( tree => 'whatever-path', control => \%controlCentre ); sub Traverse{ my %par = (@_); my $dh = OpenDir(dir=>$par{ tree }, control=>$par{control}); foreach my $file ( grep !/^\./, readdir $dh ) { my $path = "$par{tree}/$file"; if ( -d $path ) { Traverse( tree => $path, control => $par{ control } ); else { ProcessFile( name => $path, control => $par{ control } ); } } CloseDir( dh => $dh, control => $par{ control }); } sub ProcessFile{ my %par =(@_); my $fh = Open( cmd => "<$par{name}", control =>$par{control} ); # ... # process <$fh> here with any recursive calls # to ProcessFile that may be required #... Close( control => $par{ control } ), fh=>$fh ); } sub Open{ my %par = (@_); open my $fh, $par{ cmd }; my $aref=$par{ control } -> { FH }; push @$aref, $fh; # N.B. $#$aref is now one less than # the count of open files return $fh; } sub Close{ my %par = (@_); close $par{ fh }; my $aref = $par{ control } -> { FH }; my $fh = pop @$aref; ( $fh eq $par{ fh } ) or die "fh stack was abused: " . "$fh does not match $par{ fh }"; } sub OpenDir{ my %par = (@_); opendir my $dh, $par{ dir }; my $aref=$par{ control } -> { DH }; push @$aref, $dh; return $dh; } sub CloseDir my %par = (@_); closedir $par{ dh }; my $aref = $par{ control } -> { DH }; my $dh = pop @$aref; ( $dh eq $par{ dh } ) or die "dh stack was abused: " . "$dh does not match $par{ dh }"; }
-S
In reply to Re: Counting open files?
by anonymized user 468275
in thread Counting open files?
by Eyck
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |