File :: Spec-> catpath不适用于Windows

Pav*_*vel -1 windows perl path

我使用的File::Spec模块,像这样

my $volume = 'C';

my $path = File::Spec->catpath(
    $volume,
    File::Spec->catdir('panel', 'texts'),
    'file'
);

print $path;
Run Code Online (Sandbox Code Playgroud)

产量

Cpanel\texts\file
Run Code Online (Sandbox Code Playgroud)

如何在Perl中构建与OS无关的文件路径中File::Spec讨论的可移植模块如何?如果我必须写音量C:\而不只是C为了正确吗?

cjm*_*cjm 6

你有2个问题.首先是Windows卷名包括冒号,所以你应该说$volume = 'C:'.第二个是您指定了相对路径,因此您获得了相对路径.如果你想要一个绝对路径,你必须给一个:

use 5.010;
use File::Spec;

my $volume = 'C:';
my $path = File::Spec->catpath($volume,
    File::Spec->catdir('', 'panel', 'texts'), 'file');
say $path;
Run Code Online (Sandbox Code Playgroud)

在Windows上,将打印C:\panel\texts\file,在Unix上它会说/panel/texts/file.

请注意,在Windows上拥有带卷名的相对路径是完全合法的:

File::Spec->catpath('C:',
    File::Spec->catdir('panel', 'texts'), 'file');
Run Code Online (Sandbox Code Playgroud)

会给你C:panel/texts/file,这意味着panel/texts/file相对于驱动器上的当前目录C:.(在Windows中,每个驱动器都有自己的当前目录.)