如何在 Perl 中构造独立于操作系统的文件路径,包括可选的 Windows 驱动器号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1818093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I construct OS-independent file paths in Perl including an optional Windows drive letter?
提问by Sergey Stadnik
I need to construct a file path inside a Perl script. Which path separator should I use to allow my script to work on both Windows and Unix?
我需要在 Perl 脚本中构造一个文件路径。我应该使用哪个路径分隔符来允许我的脚本在 Windows 和 Unix 上工作?
Keep in mind that Windows needs a drive letter.
请记住,Windows 需要一个驱动器号。
回答by brian d foy
You want File::Spec's catpath
:
你想要File::Spec的catpath
:
catpath() Takes volume, directory and file portions and returns an entire path. Under Unix, $volume is ignored, and directory and file are concatenated. A '/' is inserted if need be. On other OSes, $volume is significant. $full_path = File::Spec->catpath( $volume, $directory, $file );
回答by s1n
You want File::Spec. There are specific versions for Unix, Win32, and MacOSas well others.
你想要File::Spec。有针对Unix、Win32和MacOS以及其他的特定版本。
回答by Schwern
If you find File::Spec cumbersome, as I do, try Path::Class. It gives you directory and file objects to work with rather than having to call long winded File::Spec class methods on strings.
如果你发现 File::Spec 很麻烦,就像我一样,试试Path::Class。它为您提供要使用的目录和文件对象,而不必在字符串上调用冗长的 File::Spec 类方法。
回答by ysth
It sounds like you are using path separator to mean the character between directory/file name components. But just in case you meant the other meaning:
听起来您正在使用路径分隔符来表示目录/文件名组件之间的字符。但以防万一你的意思是其他含义:
Some things (notably environment variables like MANPATH or PERL5LIB) take a list of file or directory names, separated by a path separator character. Perl's Config module portably supplies such a character as $Config::Config{'path_sep'}.
有些东西(特别是环境变量,如 MANPATH 或 PERL5LIB)采用文件或目录名称列表,由路径分隔符分隔。Perl 的 Config 模块可移植地提供诸如 $Config::Config{'path_sep'} 这样的字符。
回答by Mike
Q:Which path separator should I use to allow my script to work on both Windows and Unix?
问:我应该使用哪个路径分隔符来允许我的脚本在 Windows 和 Unix 上工作?
A: /.
一种: /。
Explanation: Windows can work similarly to Unix with / as path separator. (Mac OS uses : as a path separator instead of /). The File::Spec modules can also help. use File::Spec::Functions; chdir(updir()); # go up one directory $file = catfile(curdir(), 'temp', 'file.txt'); # on Unix and Win32, './temp/file.txt' # on Mac OS, ':temp:file.txt' # on VMS, '[.temp]file.txt' Source: http://www.xav.com/perl/lib/Pod/perlport.html