Can NOT List directory including space using Perl in Windows Platform

一曲冷凌霜 提交于 2020-01-02 01:49:07

问题


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.


回答1:


Try bsd_glob instead:

use File::Glob ':glob';
my @list = bsd_glob "$path/*";



回答2:


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):

my $path = shift;
$path =~ s/ /\\ /g;
my @list = glob "$path/*";

But prefer bsd_glob, it supports also a couple of other neat features, such as [] for character class.




回答3:


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:

my @list = glob "\"$path\"/*";

remember, it's a Windows solution. Whether it works under Linux depends on context.



来源:https://stackoverflow.com/questions/7898496/can-not-list-directory-including-space-using-perl-in-windows-platform

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