Learn something new about Perl every day

  Just when you think you know everything about Perl, something silly   rises up and shows you have ignorant you really are.

  How many times have you written code similar to this?

 
      my $filename = "/path/to/file.txt";
      my @dir_parts = split('/', $filename);

      my $file = pop( @dir_parts );
      my $path = join('/', @dir_parts );

or

      my ($name) = $filename =~ s/\/(.*?)$/o;

While I knew about the existance of File::Basename, the last time I looked at it I don't believe it was part of Perl Core.  I should have suspected, but now it is a standard Perl module that makes this trivial:

 
      use File::Basename;

      # Retrieve just the filename

      my $filename_only = basename($filename);

      # Get just the path in this filename

      my $path_only     = dirname($filename);


  You can get even fancier with the fileparse() function provided in
  this module.


      my ($base, $path, $suffix) = fileparse( $filename );

   Would yield the filename only in $base, the path in $path, and
   nothing in $suffix.  This is because we did not provide a regular
   expression to match on.


   If we instead used:


      my ($base, $path, $suffix) = fileparse( $filename, qr{\.txt} );

   And we ran it against $filename = '/home/frank/test.txt' and
   $filename2 = '/home/frank/test.doc' it would give us:

      Base: test
      Path: /home/frank
      Type: .txt

      and


      Base: test.doc
      Path: /home/frank
      Type:

   If the filename give to fileparse() does not match, it is not
   stripped from the basename.


It just goes to show that no matter how long you've been using Perl, or how much you think you know, there is always something out there you could be learning.

Tags: perl

Comments

I discovered exactly this fact last month and it simplified some work greatly in a setting where I could not add modules from CPAN. Another advantage to this module is that it handles Windows files and even those from some other operating systems with unusual separators.

To the Pythonistas reading this: Python has similar modules in the standard distribution, going way back to early releases, so use it as well.

by Bobbie The Programmer on Aug 6, 2007 at 10:21 AM

Comments on this post are now closed. If you want to get in touch with us to discuss this post please send us something on Twitter @revsys or use our contact form. Thanks!