Sorting files

Top Japanese page




Overview

Display files in a directory with sorting alphabetical order. For simple listing, refer to Listing files in a directory(folder). For sorting chlonological order, refer to Sorting files in updated order.

Flow

  1. Open a directory
  2. Put the contents of the directory into an array
  3. Extract the necessary files only from the array
  4. Sort the array alphabetical order
  5. 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);
 
 @filelist = sort {$a cmp $b} @filelist;
 
 print "<ul>\n";
 foreach my $file (@filelist){
    print "<li>$file</li>\n";
 }
 print "</ul>\n";

Descriptoin 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.

 @filelist = sort {$a cmp $b} @filelist;

Sort out the contents of the @filelist alphabetical order. Usually {$a cmp $b} can be omitted and code as follows;

 @filelist = sort @filelist;

To sort out reverse order,

 @filelist = sort {$b cmp $a} @filelist;

swap $a and $b as as {$b cmp $a}.

To order numbering order,

 @filelist = sort {$a <=> $b} @filelist;

use <=> as above.

To list in reverse numbering order,

 @filelist = sort {$b <=> $a} @filelist;

swap $a and $b as {$b <=> $a}.

 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.