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

Greetings ---

A novice Perl question...

I need to extract the parent directory of a file from a fully qualified file name
(e.g. /htdocs/project1/docs/file.html where the parent directory of "file.html" would obviously be "docs")

Is this a job for regex???

Thank you for your help!

Replies are listed 'Best First'.
Re: Extract Name of Parent Directory
by ctilmes (Vicar) on Jul 17, 2003 at 00:06 UTC
    use File::Basename; my $file = '/htdocs/project1/docs/file.html'; my $parent = basename(dirname($file)); print "$parent\n";
    Output:
    docs
Re: Extract Name of Parent Directory
by sauoq (Abbot) on Jul 17, 2003 at 00:12 UTC

    You can do it pretty easily with regex. You might just want to use the File::Basename though.

    $ perl -MFile::Basename -le 'print dirname("/htdocs/project1/docs/file +.html")' /htdocs/project1/docs

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Extract Name of Parent Directory
by bobn (Chaplain) on Jul 17, 2003 at 01:19 UTC

    ..

    Whew, that was rough.

    --Bob Niederman, http://bob-n.com
Re: Extract Name of Parent Directory
by LazerRed (Pilgrim) on Jul 17, 2003 at 00:16 UTC
    To go along with the example above, Perl comes with File::Basename, so you don't have to go looking for it at CPAN.

    You should do: " perldoc File::Basename " to get further info about it, as there are other functions that you may find useful.

    LR
Re: Extract Name of Parent Directory
by Coruscate (Sexton) on Jul 17, 2003 at 01:08 UTC

    Though if you *really* feel like reinventing the wheel {grin}:

    my $dir = "/htdocs/project1/docs/file.html"; my ($parent) = $dir =~ m#\A.*/([^/]+)/[^/]*\z#; print $parent, "\n";


    If the above content is missing any vital points or you feel that any of the information is misleading, incorrect or irrelevant, please feel free to downvote the post. At the same time, please reply to this node or /msg me to inform me as to what is wrong with the post, so that I may update the node to the best of my ability.

      if you *really* feel like reinventing the wheel

      Well, if you really must, at least make it short.

      my $dir = "/htdocs/project1/docs/file.html"; my $parent = (split /\//, $dir)[-2];

        man, you guys have obviously never been paid by the line of code - let's use the power of timtowtdi to make this even longer:

        my $file = "/htdocs/project1/docs/file.html"; my $elif = reverse $file; my $slash = index($elif,'/'); my $index = length( $file ) - $slash; $index--; my $dir = substr($file,0, $index); print $dir;
        You know it makes sense ;-)

        /J\