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

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

Seems simple enough, but what is the best platform-independent way to get the directory for a given file path?

I want a simple program that is given a list of files (say, output from "find") and for each file, prints the containing directory.

For example:

  $ pwd
  /home/mobiGeek
  $ perl dirs.pl  ../foo.html /etc/passwd /a/b/c/smile.gif
  /home
  /etc
  /a/b/c
Thanks in advance,
mobiGeek.
  • Comment on How do I get the directory containing a given file?

Replies are listed 'Best First'.
Re: How do I get the directory containing a given file?
by wog (Curate) on Feb 24, 2002 at 18:48 UTC
    use Cwd qw(abs_path); use File::Basename; my $dir = dirname(abs_path($file));

    Turning this into a complete perl program is left as an exercise to the reader.

      use Cwd qw(abs_path); use File::Basename; my $dir = dirname(abs_path("../foo.html"));<BR> print "dir is ($dir)\n";

      yields:

        opendir(../foo.html/..): Not a directory at text.pl line 4
        dir is ()
      

      Other ideas?

        It appears that Cwd::abs_path has issues in 5.6.1 (which seem to be fixed in bleedperl). You can get around this by reversing the calls:

        use Cwd qw(abs_path); use File::Basename; my $dir = abs_path(dirname($file));