Home: Perl Programming Help: Advanced:
List of files in a directory



benchivers
Deleted

Dec 24, 2000, 4:19 AM


Views: 3455
List of files in a directory

How do I list the files in a directory in an html page or perl script. HELP URGENTLY WANTED.



japhy
Enthusiast / Moderator

Dec 24, 2000, 7:43 AM


Views: 3453
Re: List of files in a directory

Use the opendir(), readdir(), and closedir() functions. readdir() returns a list (apparently unordered) of all the entries in a directory. Read its documentation at perldoc -f readdir.

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author


parham_m_s
journeyman

Dec 26, 2000, 6:09 AM


Views: 3442
Re: List of files in a directory

here's a little tidbit of code:

opendir (DIR,"$directory");
@files = readdir(DIR);
closedir (DIR);
foreach $line (@files) {

if ($line ne ".") {
if ($line ne "..") {
print "$line
\n";
}
}

}




japhy
Enthusiast / Moderator

Dec 26, 2000, 7:36 AM


Views: 3441
Re: List of files in a directory

I'd just like to share some code clean-up tips/hints/whatevers with you (you being everyone who decides to read this).


Code
opendir (DIR,"$directory"); 
@files = readdir(DIR);
closedir (DIR);
foreach $line (@files) {

if ($line ne ".") {
if ($line ne "..") {
print "$line
\n";
}
}

}

On line 1, you are guilty of stringificiation. You don't need to put quotes around a variable like this, when the variable is all by itself; the habit can become dangerous when you start using hard references. (Resource: "NO, THAT'S WRONG!" -- Common Perl Pitfalls (TPJ, Vol. 4, No. 2))

The rest of the code brings me to the dual nature of readdir(). You can use it to get filenames one at a time, or all at once. If you're going to get them all at once, it's easiest to do whatever filtering you need to do then, rather than store unwanted elements in an array that you need to weed through later:


Code
@files = grep $_ ne "." and $_ ne "..", readdir DIR; 
# or
@files = grep !/^\.\.?$/, readdir DIR;

The second method is a very common idiom for retrieving the entries in a directory, minus the . and .. entries.

If, however, you'd rather go through one-by-one, then you can use readdir() in scalar context:


Code
while (defined (my $entry = readdir DIR)) { 
next if $entry eq "." or $entry eq "..";
# or
next if $entry =~ /^\.\.$/;
# do something with $entry
}

I use defined() around the assignment because readdir() could very well return a 0, for a file whose name is 0, and that is a logically false value, but it is defined.

Oh, and PerlGuru Forums tip. Please wrap your code samples (nicely indented too, please, for everyone's ease) in a [pre] ... [/pre] block.

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author


parham_m_s
journeyman

Dec 27, 2000, 8:13 AM


Views: 3435
Re: List of files in a directory

thanx for the tips japhy =)
ps.. i thought html was disabled, so i didn't bother to include the pre tags =).