Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can NOT List directory including space using Perl in Windows Platform

Tags:

glob

perl

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.

like image 248
thinkhy Avatar asked Oct 26 '11 03:10

thinkhy


People also ask

How do I read the contents of a directory in Perl?

To read content of a directory, function readdir is used. In scalar context, this function will return each item of a directory one by one. Once everything is read out, it will return undef.

What is glob Perl?

glob() function in Perl is used to print the files present in a directory passed to it as an argument. This function can print all or the specific files whose extension has been passed to it. Syntax: glob(Directory_name/File_type); Parameter: path of the directory of which files are to be printed.


3 Answers

Try bsd_glob instead:

use File::Glob ':glob';
my @list = bsd_glob "$path/*";
like image 90
MVS Avatar answered Nov 15 '22 18:11

MVS


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.

like image 21
Bentoy13 Avatar answered Nov 15 '22 19:11

Bentoy13


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.

like image 25
gonesoft Avatar answered Nov 15 '22 20:11

gonesoft