Hi Monks!
I'm trying to get the canonical path of a given path (without '.', '~', '..', ... - just the unique path, string with '/'). I came across with this
question and solution. The suggested code:
foreach my $path ("/a/b/c/d/../../../e" , "/a/../b/./c//d") {
my @c= reverse split m@/@, $path;
my @c_new;
while (@c) {
my $component= shift @c;
next unless length($component);
if ($component eq ".") { next; }
if ($component eq "..") {
my $i=0;
while ($c[$i] =~ m/^\.{0,2}$/) {
$i++
}
splice(@c, $i, 1);
next
}
push @c_new, $component;
}
print "/".join("/", reverse @c_new) ."\n";
}
It works good for most cases but I had trouble with paths that start, for example, with ".." (like "../script.sh") then it gives me:
Use of uninitialized value within @c in pattern match (m//).
How can it possible to fix this code to support those cases?
Please note that I don't want to get the absolute path of the given path - meaning, I don't want to resolve any links on the way. Just to get the canonical path of the given path - starting from root, without '..', '.', '~' symbols. For example, given "../softlink/script.sh" where softlink is a link to some other area "softlink -> /a/b/c" then I want to get: "/root/to/that/path/softlink/script.sh" (I didn't resolve the link)
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.