当我使用包含尾随换行符的文件名调用perl的两个参数open()
时,该换行符将被忽略。但是,三个参数的版本保留换行符。
为什么行为不同?为什么换行符表面上被删除了?
-文件“nl”不存在。做了
$ ls -1 nl;触摸nl; ls -1 nl
ls:nl:没有这样的文件或目录
nl
-尝试三参数打开“nl\n”→ENOENT
strace显示了我期望的行为,FWIW。
$ perl -E'open(F,“<”,“nl\n”)或死亡$!'
-e第1行没有这样的文件或目录。
$ strace -e trace = open perl -E'open(F,“<”,“nl\n”)或死$!' 2>&1 | grep nl
open(“nl\n”,O_RDONLY | O_LARGEFILE)= -1 ENOENT(无此类文件或目录)
-现在,尝试使用两个参数打开“nl\n”→成功吗?
$ perl -E'open(F,“nl\n”)或死$!'
- 什么?为什么行得通?让我们看一下strace。
哦,它忽略了换行符:
$ strace -e trace = open perl -E'open(F,“nl\n”)or die $!' 2>&1 | grep nl
open(“nl”,O_RDONLY | O_LARGEFILE)= 3
-“nl”仍然是那里唯一的文件
$ ls
nl
背景:
$ perl -v
这是为i686-linux-thread-multi构建的perl 5,版本16,版本0(v5.16.0)。
最佳答案
The other important thing to notice is that, just as in the shell, any whitespace before or after the filename is ignored. This is good, because you wouldn't want these to do different things:
open INFO, "<datafile"
open INFO, "< datafile"
open INFO, "< datafile"
This is not a bug, but a feature. Because open mimics the shell in its style of using redirection arrows to specify how to open the file, it also does so with respect to extra whitespace around the filename itself as well. For accessing files with naughty names, see Dispelling the Dweomer.
There is also a 3-argument version of open, which lets you put the special redirection characters into their own argument:
…
In this case, the filename to open is the actual string in
$datafile
, so you don't have to worry about$datafile
containing characters that might influence the open mode, or whitespace at the beginning of the filename that would be absorbed in the 2-argument version. Also, any reduction of unnecessary string interpolation is a good thing.
关于perl - 为什么Perl的两个arg公开似乎剥夺了换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11253450/