Dear Monks,
Background:
I've never before bothered to make any of my code platform independent. Linux has been my predominant work platform for 8 years now. However I've recently started playing around on Windows, so have decided to explore creating code that is more platform independent.

I found the below code snippit to determine the parent directory of a script in one of my codebases:
use Cwd qw(abs_path); use File::Basename qw(dirname); my $dir_parent = abs_path(dirname(__FILE__) . '/../');
Now there is nothing inherently bad with this code. However, it hard-codes both the path separator and the .. parent directory alias. I therefore whipped out File::Spec , and come up with this monstrosity.
use File::Spec; my $dir_parent = do { my ($vol, $dir, $file) = File::Spec->splitpath( File::Spec->rel2abs(__FILE__) ); # Go up 1 directory my @dirs = File::Spec->splitdir($dir); pop @dirs while (@dirs > 1 && $dirs[-1] eq ''); # Clean up pop @dirs if @dirs > 1; # Go up 1 real directory. $dir = File::Spec->catdir(@dirs); File::Spec->catpath($vol, $dir); };
Now this code is nice in a way as it only relies on File::Spec. But, god! It's soo long!

I've therefore decided to assume that '..' is a platform specific reference. That leaves me currently with the following code:
use File::Basename qw(dirname); use File::Spec; my $dir_parent = File::Spec->rel2abs( File::Spec->catdir( dirname(__FILE__), '..' ) );
Now, I've since adapted my code to no longer need this information. However, the above two questions still remain. How would y'all determine the parent directory of a script or module in a platform independent way?

Regards,
- Miller

PS

In reply to Platform Independent Directory Traversal by wind

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.