Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Spaces in folder names...

by biswanath_c (Beadle)
on Oct 14, 2009 at 01:48 UTC ( #800997=perlquestion: print w/replies, xml ) Need Help??
biswanath_c has asked for the wisdom of the Perl Monks concerning the following question:


I am using a simple perl script that would list the names of the files in a specified directory (using glob command). But when i pass a path that has a space in a folder, the code fails! How do i escape the blank spaces in folder names>

Code shown below:
$input_folder = $ARGV[0]; print "input : $input_folder \n"; @inp_files = glob("$input_folder" . "\\*.*"); foreach $inp(@inp_files) { print "$inp" . "\n"; @filename = split(/\\/, "$inp"); $levels = scalar @filename; my $name = $filename[$levels - 1]; print "\t\t\t File Name : $name \n"; }

Replies are listed 'Best First'.
Re: Spaces in folder names...
by ikegami (Pope) on Oct 14, 2009 at 01:59 UTC

      This solution worked! Thanks a lot!

Re: Spaces in folder names...
by swampyankee (Parson) on Oct 14, 2009 at 02:20 UTC

    Since it seems you're getting the folder name from the command line, beware that white space will be used to separate individual command line arguments. If this is happening -- and I'm willing to bet XP that it is -- you'll have to try quoting the entire folder name, ("like this"). I believe there's a way to escape the white space in Windows (I know there is in most *ix shells), so dig into your shell documentation.

    Information about American English usage here and here. Floating point issues? Please read this before posting. — emc

      It has nothing to do with the shell. Despite an origin in csh, glob patterns are system independent*. Space is special to glob. It indicates a separation of patterns. For example, glob('*.h *.c') will return all C source and C header files.

      Surrounding the pattern in quotes will fail. Quotes aren't special to glob. The space can be escaped using "\". However, it's simpler to just call bsd_glob. bsd_glob is the function that implements glob, but it doesn't treat spaces specially when it's called directly.

      * — Almost. IIRC, "\" is treated literally in Windows when it isn't followed by a special character. This doesn't matter here.

        I was thinking that it did have something to do with the shell because he was getting the value for his input folder from $ARGV[0]. Since bsd_glob seemed to work with no other changes, I'll accept that the shell was not relevant.

        Information about American English usage here and here. Floating point issues? Please read this before posting. — emc

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://800997]
Approved by GrandFather
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (3)
As of 2018-04-26 22:21 GMT
Find Nodes?
    Voting Booth?