Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Answer: How do I change .. to the real filename?

by matthewm (Initiate)
on Jan 25, 2001 at 21:01 UTC ( #54293=categorized answer: print w/replies, xml ) Need Help??

Q&A > regular expressions > How do I change .. to the real filename? - Answer contributed by matthewm

To answer your specifc example..
$file =~ s%/[^/]+/\.\.$%%
... will eat the last directory name that's up'ed by the trailing ..
To give a more general/complete example that can handle multiple .'s and ..'s at any point in the path.
# colapse /./ and /.$ 1 while ($file =~ s%/\.(/|$)%$1%g); # colapse /dir/../ and /dir/..$ # ignore /../../ and /../..$ 1 while ($file =~ s%/[^/]+/(?<!/\.\./)\.\.(/|$)%$1%g); # remove ^dir/../ and ^dir/../ # ignore ^../../ and ^../.. 1 while ($file =~ s%^[^/]+/(?<!^\.\./)\.\.(/|$)%%); # colapse ^/../ to / 1 while ($file =~ s%^/\.\./%/%); # expand null to . $file =~ s%^$%.%;
We need the itterations of each loop as each substitution may reveal additional matchs.
We need multiple expressions to get the order of susbistion right. That is /../../ should colapse the two proceding directoires and not itself.
I'm sure it can be reduced more than that but it is as simple as I can see it can be and still catch all the special cases.
I use something very similar to this at the beginning of my scripts to get the conical path for $0 and not the called path. Although spliting the path into its components and working backwards is probably easier/clearer than using a regex.

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2016-10-01 20:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?






    Results (7 votes). Check out past polls.