Hello!
I am using the following PERL code to display the contents of a sub-directory on my server:

sub doit {
opendir(DIRHANDLE,"/home/username/public_html/$DirName");
@filenames = ( sort readdir(DIRHANDLE) );
foreach $dirfile (@filenames) {
print "<b><a href='/$DirName/$dirfile' target='new'>$dirfile</a></b><br><br>";
}
}

That code simply opens a directory and spits out the contents (files and sub directories in alphabetical order) -
I was wondering how I could:
1. Get perl to recognize the difference between a file and a sub-directory
2. Get perl to recognize the different file extensions.. I would like to display .html files in green, .jpg files in blue and so on..
Or maybe someone can point me to a tutorial that will help with this type of issue???

2. Get perl to recognize the different file extensions.

There are a variety of ways to determine the file extension, you could use a regexp, or split(), or substr(), and probably more. But there is a core module for this purpose: File::Basename

using your existing code as an example:

[B]use File::Basename;[/B]
$dir = '/home/username/public_html/';
$DirName = 'images';
doit();
sub doit {
   opendir(DIRHANDLE,"$dir$DirName") or die "Can't open $dir$DirName: $!";
   @filenames = sort readdir(DIRHANDLE);
   close(DIRHANDLE);
   foreach $dirfile (@filenames) {
      [B]my(undef, undef, $ftype) = fileparse($dirfile,qr{\..*});[/B]
      print "$ftype<br>";
   }
}

I would like to display .html files in green, .jpg files in blue and so on..

Building on the last example, I will use a hash table to store the color associated with the extension and the File::Basename module to get the extension and apply the color.

use File::Basename;
$dir = '/home/username/public_html/';
$DirName = 'images';
my %colors = (
   '.html' => 'green',
   '.jpg' => 'blue',
   '.gif' => 'blue', 
   '.txt' => 'red',
);
doit();
sub doit {
   opendir(DIRHANDLE,"$dir$DirName") or die "Can't open $dir$DirName: $!";
   @filenames = sort readdir(DIRHANDLE);
   close(DIRHANDLE);
   foreach $dirfile (@filenames) {
      my(undef, undef, $ftype) = fileparse($dirfile,qr{\..*});
      [B]my $color = $colors{lc($ftype)} || 'black';[/B]
      print qq~<span style="color:$color">$dirfile</span><br>\n~;
   }
}

** apply your own HTML code to the output that gets printed, mine is just for the purpose of the

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.