Escaping blog patterns

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View


I have a question about escaping the spaces in glob patterns. After 45
minutes of debugging attempts, I found out that spaces were interpreted
differently in strings of glob patterns.

Apparently spaces are like OR's, and match several criterias at once.
There's also some information about using literal spaces, but it doesn't
apply to my case.

Suppose I have a string
$glob_pattern = "/mnt/file/some dir/*";

So if I want all files in that directory, I should be able to do
@files = glob($glob_pattern);

However this doesn't work. Not even when I change the double quotes to
single quotes. Apparently one way of doing it is to declare the pattern as:
$glob_pattern = '/mnt/files/"some dir"/*';

In my case, that string ($glob_pattern) is not typed literally,
but it comes from a CGI parameter. I don't know how I would make the
change so that the string "/mnt/file/some dir/" will be interpreted as one
path, instead of two.

I hope I made myself clear. Please let me know if there are some points
that are not understood.


Re: Escaping blog patterns

Berk Birand wrote:
Quoted text here. Click to load it

If you had read the documentation on glob you would have known how it
works right off the bat, perldoc -f glob.
glob performs expansion just as a Unix shell would which treats
whitespace as pattern delimeters.

Quoted text here. Click to load it

You have a couple of options. You can simply escape spaces yourself
like so:

$glob_pattern =~ s/ /\ /g;

which will escape all spaces with a backslash and, when passed to glob,
will be treated as a single pattern.

You could also use bsd_glob which, in addition to offering more
options, does not seperate patterns by whitespace.  For example:

use strict;
use File::Glob 'bsd_glob';
my $glob_pattern = '/mnt/files/some dir/*';
my @files = bsd_glob($glob_pattern);

See the documentation on File::Glob for more information.

Robert Gamble

Re: Escaping blog patterns

Quoted text here. Click to load it

If you used an alternative to glob() you wouldn't have a question
about escaping the spaces in glob patterns.   :-)

Quoted text here. Click to load it

You could learn the alternative in less than 45 minutes...

   perldoc -f opendir
   perldoc -f readdir
   perldoc -f grep

Quoted text here. Click to load it

So you *do* already have taint checking enabled then, right?

# untested
my $dir = '/mnt/file/some dir';
my $pattern = '^\.';    # all files that do not start with dot

opendir DIR, $dir or die "could not open '$dir'  $!";
my @files = sort
            map { "$dir/$_" }
            grep /$pattern/, readdir DIR;
closedir DIR;

    Tad McClellan                          SGML consulting                   Perl programming
    Fort Worth, Texas

Site Timeline