faqts : Computers : Programming : Languages : Perl : Common Problems : File Handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

25 of 25 people (100%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How do I retrieve a list of files in a directory?

Jun 16th, 2001 06:48
Per M Knutsen,


One way of doing is with the readdir function. Example:
opendir DIRH, "/home/somedir/" || die "Cannot open: $!";
foreach (sort readdir DIRH) {
   print "This is one file: $_";
}
closedir DIRH;
Note:
This procedure will also retrieve the files . and .. that exist in 
every directory (except /). You probably don't want these. You get rid 
of these by including an if condition (with the help of a regular 
expression) in your foreach loop, eg.:
opendir DIRH, "/home/somedir/" || die "Cannot open: $!";
foreach (sort readdir DIRH) {
   if ($_ !~ m/^\.+$/) {
      print "This is a real file: $_";
   }
}
closedir DIRH;