Using File::Basename to get file extensions

KevinADC 0 Tallied Votes 812 Views Share

The File::Basename module is used to parse file paths into directory, filename and suffix (or file extension). My simple example shows how to get just the file extensions.


use strict;
use File::Basename;
use CGI qw/:standard/; #if running as a CGI application
#use CGI::Carp qw/fatalsToBrowser/; # uncomment for debugging only
print header,start_html; # if running as a CGI application

my $dir = '/home/username/public_html';
opendir(DIRHANDLE,$dir) or die "Can't open $dir: $!";
my @filenames = sort readdir(DIRHANDLE);
foreach my $file (@filenames) {
   my(undef, undef, $ftype) = fileparse($file,qr"\..*");
   print "$ftype<br>\n";
print end_html; #if running as a CGI application