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

07.06.2007
| 32057 views |
  • 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; }
    

Comments

Snippets Manager replied on Mon, 2007/07/16 - 11: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 (http://search.cpan.org/~nwclark/perl-5.8.8/lib/File/Basename.pm) module off of CPAN, which works marvelously. Plus, it is part of the default Perl distribution so its on every machine.