-   Programming (
-   -   Perl, Removing file from path to get directory only (

xemous 05-22-2006 06:38 AM

Perl, Removing file from path to get directory only
I need to remove the file name from a path, eg:

$fpath = /home/user/hello/

So I can make it...

$fpath2 = /home/user/hello


Is there an easy way to do this, like some inbuilt function?

druuna 05-22-2006 07:14 AM


Take a look at: File::Basename

It can do a lot more then you ask, with that in mind here's a code snippet:



use strict;
use warnings;

use File::Basename;

my $fpath = "/home/user/hello/";

print "Original  : " . $fpath . "\n";

my($filename, $directories) = fileparse($fpath);

print "Filename  : " . $filename    . "\n";
print "Directory : " . $directories . "\n";

Hope this helps.

xemous 05-22-2006 01:44 PM

I love you.

introuble 05-23-2006 12:32 AM

*Or* (I don't see much reason to do this but..) you can use the dirname(1) utility.

druuna 05-23-2006 09:25 AM


True, you could use dirname (1), but it's an external (unix) command, seen from perl that is.

dirname [File::Basename] (3) is also part of File::Basename and an internal perl command, which is more resource friendly.

Hope this clears things up a bit.

vammydhar 09-02-2008 01:53 PM

Thanks for the above soultion

druuna 09-02-2008 02:12 PM


You are welcome!

isisira 04-11-2012 12:25 AM

Thank you
Hi! Thank you.. A colleague today asked me how to do this and I directly got the answer when i came here..perfectly worked!

theNbomr 04-11-2012 11:13 AM

The Perl code to do this can be as simple as (if $filename contains fully qualified filespec):


Relies on greedy matching that is default in Perl.

--- rod.

All times are GMT -5. The time now is 01:26 PM.