RSS

Perl – How To: fileparse

23 Oct

perl.org

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

In this post I cover the interesting use of one of the important Perl File::Basename routines: fileparse().

The File:Basename core module parses the file paths into directory, filename and suffix.

($name,$path,$suffix) = fileparse($fullname,@suffixlist);

My requirement was parse the file path string, and process the file only if the file extension (suffix) is, say, .t or .txt.

In that case one can go ahead and create an array of extensions and use fileparse utility for parse the string for suffix and go ahead..

#File Name: test.pl
#Introduction: Verify fileparse routine

use File::Basename;

@exts = qw(.t .txt);

$mypath=”/home/user/dir1/dir2/file3.txt”;

my($base, $path, $ext) = fileparse($mypath, @exts);

print (” path: $path\n base: $base\n ext: $ext\n”);

The expectation was to get .txt suffix parsed correctly so that I can process the file. However that was not the case, and I got output as:

$perl test.pl
path: /home/user/dir1/dir2/
base: file3.t
ext: xt

After analyzing the output, I realized the approach of using the extension array (@exts) is not helping me.. Then understood that fileparse can also take a regex (as in my case: ‘\..*’) as second argument, which did the trick! This solution assumes there is only one dot (‘.’) in the filename before suffix and searches for the first one and does the processing!

#File Name: test.pl
#Introduction: Verify fileparse routine

use File::Basename;

$mypath=”/home/user/dir11/dir22/file33.txt”;

my($base, $path, $ext) = fileparse($mypath, ‘\..*’);

print (” path: $path\n base: $base\n ext: $ext\n”);

And the output:

$perl test.pl
path: /home/user/dir11/dir22/
base: file33
ext: .txt

There is one more ‘regex’ way:
If you have more than one dot (‘.’) in the filename and the requirement is to get the last dot and process, then the regex would change to qr/\.[^.]*/:

#File Name: test.pl
#Introduction: Verify fileparse routine

use File::Basename;

$mypath=”/home/user/dir111/dir222/file333.txt.t.txttxt”;

my($base, $path, $ext) = fileparse($mypath, qr/\.[^.]*/);

print (” path: $path\n base: $base\n ext: $ext\n”);

And the output:

$perl test.pl
path: /home/user/dir111/dir222/
base: file333.txt.t
ext: .txttxt

Advertisements
 
Leave a comment

Posted by on October 23, 2011 in Perl, Technical

 

Tags: , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: