http://www.perlmonks.org?node_id=80207

psmail has asked for the wisdom of the Perl Monks concerning the following question: (strings)

I need to separate the filename and path from a string. e.g.
$a = "/root/subroot/subsubroot/filename"; I want to separate filename and the path. i.e. The output should be $b = "/root/subroot/subsubroot/" $c = "filename"
Thanks

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I split a string containing path+filename
by arturo (Vicar) on May 14, 2001 at 18:30 UTC

    For maximum portability, use File::Basename, a standard CPAN module:

    use File::Basename; use strict; # get full path in $path my $filename = basename($path);
Re: How do I split a string containing path+filename
by grinder (Bishop) on May 15, 2001 at 12:34 UTC

    The complement to basename that arturo forgot to mention is dirname, so your code would look like this:

    $a = "/root/subroot/subsubroot/filename"; $b = dirname $a; $c = basename $a;

    That said, do not get into the habit of using variables $a and $b. You are much better off giving them descriptive names, which will help your code self-document itself. A better way of writing your code would be

    my $filespec = "/root/subroot/subsubroot/filename"; my $path = dirname $filespec; my $filename = basename $filespec;
Re: How do I split a string containing path+filename
by tye (Sage) on May 15, 2001 at 20:01 UTC
Re: How do I split a string containing path+filename
by tachyon (Chancellor) on May 21, 2001 at 08:50 UTC
    Quick and dirty regex answer (for Unix or DOS):
    ($b,$c) = $a =~ m|^(.*[/\\])([^/\\]+?)$|;
    I agree with grinder that your var names are obfu, which has its place, but usually we choose descriptive names like $p and $f or even $pathname and $filename ;-)
Re: How do I split a string containing path+filename
by frank1982 (Initiate) on Mar 31, 2017 at 10:24 UTC

    Re: How do I split a string containing path+filename

    Originally posted as a Categorized Answer.