DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Basename & Dirname In Perl

  • submit to reddit
        These two Perl functions implement approximations of the UNIX utilities `basename` and `dirname`, though basename() automatically strips off the last extension no matter what.
sub basename($) {
 my $file = shift;
 $file =~ s!^(?:.*/)?(.+?)(?:\.[^.]*)?$!$1!;
 return $file;

sub dirname($) {my $file = shift; $file =~ s!/?[^/]*/*$!!; return $file; }


Snippets Manager replied on Mon, 2007/07/16 - 10:52am

That is definitely an interesting way of doing this while not using any modules. Just as a reference, you can use the File::Basename ( module off of CPAN, which works marvelously. Plus, it is part of the default Perl distribution so its on every machine.