How can I construct OS-independent file paths in Perl including an optional Windows drive letter?

旧街凉风 提交于 2020-01-10 10:49:12

问题


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?

Keep in mind that Windows needs a drive letter.


回答1:


You want File::Spec's 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 );



回答2:


You want File::Spec. There are specific versions for Unix, Win32, and MacOS as well others.




回答3:


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.




回答4:


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'}.




回答5:


Q:Which path separator should I use to allow my script to work on both Windows and 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


来源:https://stackoverflow.com/questions/1818093/how-can-i-construct-os-independent-file-paths-in-perl-including-an-optional-wind

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!