Why does Perl two arg open seem to strip newlines?

When I call perl two-arg open() with a file name containing a trailing newline, the newline is ignored. However, the version with three arguments saves the new line.

Why is the behavior different? Why is the anchor out of order?

- The file "nl" does not exist. Do it

  $ ls -1 nl;  touch nl;  ls -1 nl
 ls: nl: No such file or directory
 nl 

- Try tri-arg to open "nl \ n" -> ENOENT

strace shows the behavior that I expect, FWIW.

  $ perl -E 'open (F, "<", "nl \ n") or die $!'
 No such file or directory at -e line 1.

 $ strace -e trace = open perl -E 'open (F, "<", "nl \ n") or die $!'  2> & 1 |  grep nl
 open ("nl \ n", O_RDONLY | O_LARGEFILE) = -1 ENOENT (No such file or directory) 

- Now try two-arg open "nl \ n" โ†’ success?

  $ perl -E 'open (F, "nl \ n") or die $!' 

- What? Why did it work? Look at strace.

Oh, he ignores the new line:

  $ strace -e trace = open perl -E 'open (F, "nl \ n") or die $!'  2> & 1 |  grep nl
 open ("nl", O_RDONLY | O_LARGEFILE) = 3 

- "nl" is still the only file there

  $ ls 
 nl 

Background:

  $ perl -v 

This is perl 5, version 16, subversion 0 (v5.16.0), built for i686-linux-thread-multi.

+6
source share
2 answers

perldoc perlopentut :

Another important note is that, as in the shell, any spaces before or after the file name are ignored. This is good because you would not want them to do different things:

 open INFO, "<datafile" open INFO, "< datafile" open INFO, "< datafile" 

This is not a mistake, but a function. Since open mimics a shell in its style of using redirection arrows to indicate how to open a file, it also does this with respect to extra spaces around the file name itself as Well. To access files with naughty names, see Dweomer Resettlement .

There is also a version with three open arguments that allows you to put special redirection characters in your own argument:

& hellip;

In this case, the file name being opened is the actual string in the $ $datafile , so you donโ€™t need to worry about the $datafile containing characters that can affect open mode, or spaces at the beginning of the file name that will be absorbed by the version with two arguments. In addition, any reduction in unnecessary line interpolation is good.

+11
source

This is pretty simple: since the 2-arg open syntax approximates the shell, even to the pipe resolution point.

+2
source

Source: https://habr.com/ru/post/919282/


All Articles