Listing files in a directory(folder)

Top Japanese page




Overview

Display file list in a directory on a server.

Flow

  1. Open a directory
  2. Put the contents in the directory into an array
  3. Extract necessary files from the array
  4. Display the contents of the array

A sample code

 my $dir = "filedir";
 
 opendir(DIR, "$dir") or die "Cannot open $dir;
 my @filelist = grep !/^\./, readdir DIR;
 closedir(DIR);
 
 print "<ul>\n";
 foreach my $file (@filelist){
    print "<li>$file</li>\n";
 }
 print "</ul>\n";

Description of the code

 my $dir = "filedir";
 
 opendir(DIR, "$dir") or die "Cannot open $dir;
 my @filelist = grep !/^\./, readdir DIR;
 closedir(DIR);

$dir contains the directory name you want to display the contents of. Open the directory by opendir. If failed, terminate script with a error message. Read out the contents of the file handle DIR using readdir. The read data is pruned by grep and extract the necessary files and put them into the array @filelist. In this example, the all files except the files starting from dot. Then close the file handle DIR.


 print "<ul>\n";
 foreach my $file (@filelist){
    print "<li>$file</li>\n";
 }
 print "</ul>\n";

Display the files stored in @filelist. In this example, put <li></li> for convenience. You can execute any necessary processes if you want. If you want to sort out, refer to Sorting files and Sorting files in updated order.