简体   繁体   中英

why perl testing dir -d “ ” on windows returns true? bug or not?

Is there any explanation for perl returning true when testing a space-string dir on Windows? Run on Windows7:

  perl -e "print qq{found\n} if -d qq{ }"

You will get output: found

But same perl code returns false on Linux.

Tested on perl 5.8 and strawberry perl 5.18 on Windows

Is it a bug or have an unconventional reasoning?

Under windows, any perl operation that internally tries to test a file or directory for existence uses the Win32 function CreateFile . Under windows a filename ending in spaces is not legal (although not clearly documented), and for some strange reason the CreateFile function internally strips all trailing spaces before trying to open the file/directory.

Since a name starting with space looks like a relative path, the space is first appended to your current working directory but then internally ignored by the Win32 function. This results in the directory test seeing your current directory and reporting success.

The perl stat function then proceeds to acquiring additional information and seems to somewhere down the line handle the trailing space(s) differently and therefore fails to get any further information. However it seems to explicitly leave the mode attribute of the stat result set, because it earlier had deduced that there existed a directory.

So yes, I would call this a bug in the windows port of perl, but fixing it is probably not as easy as it sounds, as there are lots of special cases for UNC paths, reparse points, NTFS/FAT filesystems etc. that makes correct handling of trailing spaces rather tricky.

Your best bet would probably be to explicitly strip trailing spaces from any assumed directory name at a very early point (who needs that anyway) and croak if nothing is left after stripping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM