Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

How do I split a string containing path+filename

by psmail (Initiate)
on May 14, 2001 at 18:23 UTC ( [id://80207]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://80207]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-25 21:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found