Using File::Basename to get file extensions

KevinADC

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.

737 Views
About the Author
#!/usr/bin/perl

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);
close(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