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

Hi Monks, If I have a variable such as
$temp1 = "/proj/home/me/asdf.pl"; or $temp1 = "asdf1.pl";
what code can i do to extract only the directory path only? ie "/proj/home/me/" for first one and none for the second one

Replies are listed 'Best First'.
Re: Data Extraction Question
by Corion (Patriarch) on Aug 03, 2004 at 12:36 UTC

    Use the File::Basename module:

    use strict; use File::Basename; while (<DATA>) { chomp; my $dir = dirname $_; my $file = basename $_; print "I am '$file' in '$dir'.\n"; }; __DATA__ /proj/home/me/asdf.pl asdf1.pl foo/asdf.pl

    Another alternative might be the FindBin module:

    use strict; use FindBin; print "I am in '$FindBin::Bin'.";
Re: Data Extraction Question
by Gilimanjaro (Hermit) on Aug 03, 2004 at 14:30 UTC
    If you may need the filename later on:
    my ($directory) = $fullpath =~ m|^(.*/)?|;
    This will slurp as much as it can, as long as it's followed by a slash. $directory will be undefined if there isn't one in there... Or
    my ($directory) = $fullpath =~ m|^(?:(.*)/)?|;
    if you don't like the trailing slash on the path...
Re: Data Extraction Question
by tsr2 (Initiate) on Aug 03, 2004 at 12:38 UTC
    Something like
    $dir = $templ; $dir =~ s%/[^/]+$%/%;
    Essentially it deletes everything to the right of the last '/' character found.
    Caution: I haven't tested this.
      This is not completely correct, I think:

      for /proj/home/me/asdf.p your code would correctly give: /proj/home/me/

      but for asdf1.pl the result would be: asdf1.pl

      another approach:

      my $temp1 = "/proj/home/me/asdf.pl"; print my_dirname($temp1) ."\n"; $temp1 = "asdf1.pl"; print my_dirname($temp1) ."\n"; $temp1 = "/asdf1.pl"; print my_dirname($temp1) ."\n"; sub my_dirname { my ($dir) = $_[0] =~ m|^(.*/)|; return $dir; }

      ---- amphiplex