
japhy
Enthusiast
/ Moderator
Dec 26, 2000, 7:36 AM
Post #4 of 5
(2909 views)
|
Re: List of files in a directory
[In reply to]
|
Can't Post
|
|
I'd just like to share some code clean-up tips/hints/whatevers with you (you being everyone who decides to read this).
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:
@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:
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
|