如何在 Perl 中将文件路径更正为操作系统特定的路径?
由于一些混乱的遗留代码,
我
$path = [OS specific base DIR name][hardcoded Linux file path]
在 Linux 上有这样的情况,
$path = /common/path/to/dir/pathtofile/name.extension
但在 Windows 上它变成了这样
$path = C:\path\to\dir\pathtofile/name.extension
有些代码在 Windows 上失败,因为它需要一个 \
而它得到一个 /。
有 Perl 函数可以帮助我吗?
类似
print "$path\n";
$path = <some function> $path;
print "$path\n";
C:\path\to\dir\pathtofile/name.extension
C:\path\to\dir\pathtofile\name.extension
Due to some messed up legacy code,
I have
$path = [OS specific base DIR name][hardcoded Linux file path]
So on Linux, it is something like
$path = /common/path/to/dir/pathtofile/name.extension
but on Windows it becomes this
$path = C:\path\to\dir\pathtofile/name.extension
Some of the code fails on Windows because it is expecting a \
while it gets a /
.
Is there a Perl function that can help me here?
Something like
print "$path\n";
$path = <some function> $path;
print "$path\n";
C:\path\to\dir\pathtofile/name.extension
C:\path\to\dir\pathtofile\name.extension
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
File::Spec
系列模块完全存在因为这个原因。您可能需要考虑使用它而不是硬编码 UNIX 路径。如果您确实需要在某个地方硬编码 unix 路径(这看起来确实不是一个好主意),您可能应该使用 File::Spec::Unix 将路径拆分为其组件,然后使用目标系统本机的
File::Spec
变体来构建,将组件重新组合在一起。The
File::Spec
family of modules exists exactly for that reason. You might want to consider using that instead of hardcoding unix paths.If you really need to hardcode unix paths somewhere, which really doesn't seem like a good idea, you should probably use
File::Spec::Unix
to split up the path into its components, and then use theFile::Spec
variant native to your target system to build put the components back together again.您是否看过 File::Spec 核心模块以及相关模块?
Have you looked at the File::Spec core modules - and related ones?
听起来您好像是从其他地方将整个 $path 作为一个单元传递给您,而不是单独处理各个部分。在这种情况下,如果我们在 Windows 下运行,我认为没有比用反斜杠替换所有斜杠的丑陋解决方案更好的答案了。
以下内容应该可以满足您的需要:
编辑:再想一想 - 看了 File::Spec 后,看起来您想要
canonpath
函数:It sounds like you're getting the entire $path handed to you from somewhere else as one unit, rather than having the luxury of dealing with the pieces separately. In which case, I don't see a better answer than the ugly solution of replacing all slashes with backslashes if we're running under Windows.
The following should do what you need:
EDIT: On second thought -- having taken a look at File::Spec, it looks like you want the
canonpath
function: