无法在 Windows 平台中使用 Perl 列出包含空间的目录
为了列出Windows中的路径,我编写了下面的Perl函数(在StrawBerry运行环境下执行)。
sub listpath
{
my $path = shift;
my @list = glob "$path/*";
#my @list = <$path/*>;
my @pathes = grep { -d and $_ ne "." and $_ ne ".." } @list;
}
但它无法正确解析包含空格的目录,例如:
当我发出以下代码时: listpath("e:/test/test1/test11/test111/test1111/test11111 - 复制");
该函数返回一个包含两个元素的数组:
1: e:/test/test1/test11/test111/test1111/test11111 2: -
我想知道 glob 是否可以解析上面的空间目录。多谢。
In order to list pathes in Windows,I wrote below Perl function(executed under StrawBerry runtime environment).
sub listpath
{
my $path = shift;
my @list = glob "$path/*";
#my @list = <$path/*>;
my @pathes = grep { -d and $_ ne "." and $_ ne ".." } @list;
}
But it can't parse directory including space correctly, for example:
When I issued following code:
listpath("e:/test/test1/test11/test111/test1111/test11111 - Copy");
The function returned an array including two elements:
1: e:/test/test1/test11/test111/test1111/test11111
2: -
I am wondering if glob could parse above space directories. Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用
bsd_glob
代替:Try
bsd_glob
instead:即使这个话题很久以前就已经得到回答,我最近遇到了同样的问题,快速搜索给了我另一个解决方案,来自 perlmonks(最后回复):
但更喜欢
bsd_glob
,它还支持一些其他简洁的功能,例如用于字符类的[]
。Even if the topic has been answered long time ago, I recently encounter the same problem, and a quick search gives me another solution, from perlmonks (last reply):
But prefer
bsd_glob
, it supports also a couple of other neat features, such as[]
for character class.问题是关于 Windows 平台的,Bentoy13 的解决方案在 Windows 平台上不起作用,因为反斜杠会被误认为是路径分隔符。
如果出于某种原因您不想使用 bsd_glob,这里有一个选项:将路径的进攻部分用双引号引起来。这可以是一个目录名称 (
path\\"to my"\\file.txt
) 或多个目录名称 ("path\\to my"\\file.txt
) >)。斜杠代替反斜杠通常也有效。当然,它们不必包含空格,因此这里始终有效:记住,这是 Windows 解决方案。它是否在 Linux 下运行取决于上下文。
The question is about Windows platform, where Bentoy13's solution does not work because the backslash would be mistaken for a path separator.
Here's an option if for whatever reason you don't want to go with bsd_glob: wrap the offensive part of the path in double quotes. This can be one directory name (
path\\"to my"\\file.txt
) or several directory names ("path\\to my"\\file.txt
). Slash instead of backslash usually works, too. Of course, they don't have to include a space, so this here always works:remember, it's a Windows solution. Whether it works under Linux depends on context.