variable scope

S

sonet

The code print file in directory.But i have a question about the
variable scope.

Directory tree:
file: /usr/local/app/f1
file: /usr/local/app/f2
dir: /usr/local/app/d1
dir: /usr/local/app/d1/d2

If i use opendir(DIR,$path) not opendir(my $DIR,$path). The code
will terminate. Becase the FILEHANDLE closed as the main loop is
running.

When the code run at /usr/local/app/d1 , It have not terminate.
It will call self(recursive).Why the variable($path) in main loop
will not influence each other?

------------------------------------------------------------------------------------
my $dir='/usr/local/app';
listdir("$dir");

sub listdir{
my $path=shift;
opendir(my $DIR,$path);
while(my $file=readdir($DIR)){
if (-f "$path/$file"){
print "$path/$file\n";
}elsif (-d "$path/$file" && $file ne '.' && $file ne '..'){
listdir("$path/$file");
}
}
close($DIR);
}
 
B

Brian McCauley

opendir(my $DIR,$path);
close($DIR);

Tad has addressed your actual question but I would like to point out
that close() above does nothing. Potentially $DIR (which is a GLOBref)
actually holds both a filehandle and a directory handle (and a scalar,
and an array and so on...). Of these potential things only the
directory handle is used.

To close the directory handle.

closedir($DIR);

But if you are not checking for failure anyhow you may as well not
bother. It'll be closed implicitly when the last reference to the GLOB
goes away. Unless you've made any persistant copies this'll be when
$DIR goes out of scope.
 
J

Joe Smith

sonet said:
If i use opendir(DIR,$path) not opendir(my $DIR,$path). The code
will terminate. Becase the FILEHANDLE closed as the main loop is
running.

opendir(DIR,$path);
while(my $file=readdir(DIR)){

You're using readdir() in scalar context. That does not work when
a single dirhandle is being used in a recursive manner.

If you insist on using DIR instead of a lexical variable, you should
use it and close it before any recursion takes place.

opendir(DIR,$path) or die;
my @files = readdir(DIR);
close DIR:
foreach my $file (@files) {


-Joe
 

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,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top