可能的重复:
如何在 Perl 中查找用户的主目录?< /a>
我正在运行 Ubuntu。
每当我向 Perl 脚本传递以 ~
开头的路径(例如 ~/Documents/file.txt
)时,它都无法找到它。我必须传递规范路径(例如 /home/dave/Documents/file.txt
)。
这是为什么?
我可以让 Perl 识别 ~
路径吗?
更新
所有建议的解决方案都包括更改脚本中的代码。我想要一个不涉及对脚本本身进行任何更改的解决方案(因为并非所有脚本都是我的)。也许 Bash 的工作方式有问题?
问题的更新版本已发布在超级用户。
Possible Duplicate:
How do I find a user's home directory in Perl?
I'm running Ubuntu.
Whenever I pass a Perl script a path that starts with ~
(e.g. ~/Documents/file.txt
) it fails finding it. I must pass the canonical path (e.g. /home/dave/Documents/file.txt
).
Why is that?
Can I make Perl recognize ~
paths?
UPDATE
All the suggested solutions include changing the code in the scripts. I would like for a solution that would not involve any changes to the scripts themselves (since not all of them are mine). Perhaps something in the way Bash works?
The updated version of the question was posted at Super User.
发布评论
评论(7)
您可以将路径传递给
glob
来扩展它。You can pass the path to
glob
to get it expanded.要获得可靠(且简单)的跨平台方法,请尝试 File::HomeDir:
For a reliable (and easy) cross-platform method, try File::HomeDir:
glob 函数理解标准 Unix 文件通配。
The glob function understands standard Unix file globbing.
尝试将
~
替换为$ENV{HOME}
Try to replace
~
with$ENV{HOME}
根据 Bruno 的评论,您可以这样做:
e
标志将表达式替换为执行或评估的结果 em> 替换表达式。From Bruno's comment, you could do it this way:
The
e
flag replaces the expression with the result of executing or evaluating the replace expression.使用尖引号,而不是双引号:
迭代运算符,人们通常认为它是readline
函数的语法糖,而是调用xxx 中有 shell 元字符,则 >glob 函数,并且波形符算作其中之一。
您可能更喜欢
<:encoding(Latin1)
的开放模式。这仅取决于文件。Use angle-quotes, not double-quotes:
The
<xxx>
iteration operator, which people usually think of as syntactic sugar for thereadline
function, instead calls theglob
function if there are shell metachars in xxx, and tilde count as one of those.You might prefer an open mode of
<:encoding(Latin1)
. It just depends on the file.有点晚了,但一个简单的解决方案是双重转义文件名/路径中的空格,这样 glob 就不会破坏。不太确定它是否可移植,但在支持此功能的平台上(甚至可能是 Windows?)很容易做到,然后将结果值存储在 var 中以便于使用。可以使用正则表达式用双反斜杠转义符替换文件名中的空格。示例,无正则表达式:
Kind of late to this one, but an easy solution is to double escape the spaces in a filename/path so that glob doesn't break. Not so sure it's portable, but it's easy enough to do on platforms that support this (maybe even windows?) and then the resultant value stored in a var allows for easy usage. A regex could whipped up to replace spaces in filenames with a double backslash escape. Example, sans regex: