8

I have a folder, its name is:

drwxr-xr-x. 2 user user 4096 Aug 2 18:30 folder name [www.website.com] 

but when I use the glob like this:

my @files = glob ("/home/user/Downloads/folder name [www.website.com]/*"); print "@files\n"; 

it does not list the files in the directory, the result is the following:

/home/user/Downloads/folder name 

I have tried escaping the whitespaces and the square brackets like this:

/home/user/Downloads/folder\ name\ \[www.website.com\] 

But the result is the same, What could be my mistake or What could do to improve my code?

Thanks in advance

0

2 Answers 2

9

The builtin glob function splits patterns at whitespace. So you are doing something equivalent to

my @files = ( glob("/home/user/Downloads/folder"), glob("name"), glob("[www.website.com]/*"), ); 

Escaping the whitespace and the brackets would be one option. But it is better to use the core File::Glob module for finer control:

use File::Glob ':bsd_glob'; my @files = bsd_glob("/home/user/Downloads/folder name \\[www.website.com\\]/*"); 

Now, only the brackets need to be escaped. This also overrides the builtin glob, so you don't actually have to change your code except for that one import (and of course, the pattern).

Sign up to request clarification or add additional context in comments.

4 Comments

On Perl version 5.14, I need to use File::Glob ':glob';. It looks like :bsd_glob was added in 5.16.
@toolic From the docs: The :glob tag, now discouraged, is the old version of :bsd_glob. It exports the same constants and functions, but its glob() override does not support iteration i.e. can cause infinite loops. It seems the :bsd_glob was added in perl 5.016. If back-compat is neccessary, judicious use of :glob seems the correct thing to do.
@ikegami Thank you for that correction, I edited my answer accordingly. It seems I misremembered some recent posts of yours on p5p as “no whitespace escaping at all”.
Importing bsd_glob, without colon, works also with older perls.
1

Spaces and square brackers are special in glob patterns. To match

/home/user/Downloads/folder name [www.website.com] 

you need

/home/user/Downloads/folder\ name\ \[www.website.com\] 

So the full pattern is

/home/user/Downloads/folder\ name\ \[www.website.com\]/* 

To build that string, you could use the string literal

"/home/user/Downloads/folder\\ name\\ \\[www.website.com\\]/*" 

Test:

$ perl -E'say for glob "/home/eric/Downloads/folder\\ name\\ \\[www.website.com\\]/*"' /home/eric/Downloads/folder name [www.website.com]/foo 

Note that spaces cannot be escape in Windows. You'd have to use File::Glob's bsd_glob. (It's calls the same function as glob, but with different flags.)

use File::Glob qw( bsd_glob ); say for bsd_glob("C:\\Program Files\\*"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.