Sunday, December 28, 2008

Perl : Get filename or directory name from an absolute path

Use Perl's File module to get Filename or directory name from an absolute path. Below is an example of how to do this:

#!/usr/bin/perl
use File::Basename;

print getDirPath("/mnt/users/vishnu/blog/PerlPost.html");
print getFileNameWithoutExt("/mnt/users/vishnu/blog/PerlPost.html");
print getFileName("/mnt/users/vishnu/blog/PerlPost.html");

sub getDirPath() {
return dirname($_[0]);
}

sub getFileNameWithoutExt() {
my $file = basename($_[0]);
$file =~ s/\.[^.]*$//;
return $file;
}

sub getFileName() {
return basename($_[0]);
}


Output of above program would be:
/mnt/users/vishnu/blog
PerlPost
PerlPost.html

No comments: