devlele has asked for the wisdom of the Perl Monks concerning the following question:


I have a list of pathnames in an array such as "C:\dir1\", "C:\dir1\subdir1\", "C:\dir1\subdir1\subdir2\", "C:\dir1\subdir1\subdir2\subdir3\" etc. Now I am interested in getting just "subdir1" from the entire array so I am using a regular expression  ($_ =~ /(^C:\\$dir\\)(.*)(\\$)/) where $dir is "dir1" and $2 should give me "subdir1". But with this above all cases match. I just want to get subdir1. What should I use ?

Please help.
Thanks.

Replies are listed 'Best First'.
Re: how do I get the directory name from the pathnames
by jZed (Prior) on Dec 21, 2005 at 16:14 UTC

      I am getting all the pathnames which I mentioned by parsing an xml file and not from the file system. Do you still think that using File::Basename will solve the probelm.

      Please let me know.
        Yes, it will. It works on strings and breaks them into directory, file, extension, etc. It is portable. It is easy.
Re: how do I get the directory name from the pathnames
by ikegami (Patriarch) on Dec 21, 2005 at 16:41 UTC

    If you know the input will be of that form [as opposed to
    c:\dir1\subdir1 (lowercase C:),
    \dir1\subdir1 (no drive),
    dir1\subdir1 (relative path) or
    C:/dir1/subdir1 (alternate slashes)
    ], the following will do the trick:

    my ($subdir1) = /^C:\\[^\\]+\\([^\\]+)/;

    Otherwise, use core module File::Spec. (I don't see how File::Basename would help.)

    use File::Spec (); my ($subdir1) = (File::Spec->splitdir(File::Spec->rel2abs($_)))[2];
Re: how do I get the directory name from the pathnames
by prasadbabu (Prior) on Dec 21, 2005 at 16:15 UTC
Re: how do I get the directory name from the pathnames
by ptum (Priest) on Dec 21, 2005 at 16:19 UTC

    If you don't know where in the path subdir1 will fall, then you may prefer to split the string using the '\' character as a separator.

    If you are always after the second token, then something like this may work:

    if (/^C:\\.*?\\(.*?)\\.*$/) { $subdir1 = $1; }

    You may also find File::Basename helpful.


    No good deed goes unpunished. -- (attributed to) Oscar Wilde
Re: how do I get the directory name from the pathnames
by GrandFather (Saint) on Dec 21, 2005 at 19:26 UTC

    Use splitpath from File::Spec and split:

    use strict; use warnings; use File::Spec; while (<DATA>) { chomp; my @subs = split /\\/, (File::Spec->splitpath ($_)) [1]; print "sub dir is: $subs[2]\n" if $#subs > 1; print "No sub dir in $_\n" if $#subs <= 1; } __DATA__ C:\dir1\ C:\dir1\subdir1\ C:\dir1\subdir1\subdir2\

    Prints:

    No sub dir in C:\dir1\ sub dir is: subdir1 sub dir is: subdir1

    DWIM is Perl's answer to Gödel