Can NOT List directory including space using Perl

2020-08-25 05:10发布

问题:

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.



标签: perl glob