如何串联路径名和相对路径名? [英] How to concatenate pathname and relative pathname?

查看:79
本文介绍了如何串联路径名和相对路径名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务需要连接2个路径名:perl中的绝对+相对.下面介绍了我要实现的目标:

I have a task where I need to concatenate 2 pathnames: absolute + relative in perl. The following describes what I am trying to achieve:

dir1/dir2/dir3/ + ../filename => dir1/dir2/filename
dir1/dir2/dir3/ + ../../filename => dir1/filename

我唯一的解决方案是在相对路径中计数"..",例如X,然后将绝对路径拆分为dirs并对其进行计数-Y,最后仅将Y-X dirs与文件名连接起来.这似乎太庞大了,我想知道是否存在更好的解决方案(我敢肯定).预先谢谢你.

I have only solution that counts ".." in relative path, say X, then splits the absolute path into dirs and count them - Y and finally concatenates only Y-X dirs with filename. This seems too bulky and I wonder whether better solution exists (I am sure it does). Thank you in advance.

推荐答案

$ perl -MURI -E'say URI->new($ARGV[1])->abs($ARGV[0]);' \
    http://foo.com/dir1/dir2/dir3/ ../filename
http://foo.com/dir1/dir2/filename

$ perl -MURI -E'say URI->new($ARGV[1])->abs($ARGV[0]);' \
    http://foo.com/dir1/dir2/dir3/ ../../filename
http://foo.com/dir1/filename

它甚至可以与您拥有的两个相对URL一起使用.

It even works with two relative URLS like the ones you have.

$ perl -MURI -E'say URI->new($ARGV[1])->abs($ARGV[0]);' \
    /dir1/dir2/dir3/ ../filename
/dir1/dir2/filename

$ perl -MURI -E'say URI->new($ARGV[1])->abs($ARGV[0]);' \
    /dir1/dir2/dir3/ ../../filename
/dir1/filename

这篇关于如何串联路径名和相对路径名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆