英文:
Where does this \r\n come from when I redirect STDOUT to a PTY in Perl?
问题
以下是要翻译的内容:
"parent [1]: "foo\n"
child [1]: "foo\n"
child [2]: "bar\n"
parent [2]: "bar\r\n""
但是在最后一行,我预期收到 "bar\n"。而且,我在Linux下运行Perl,所以这个LF转CRLF的问题不应该存在,对吗?
英文:
With the following code:
use strict;
use warnings;
use utf8;
use IO::Pty;
use Data::Dump qw(pp);
my $pty = IO::Pty->new;
open *STDOUT, '>&', $pty->slave;
if ( my $pid = open *STDOUT, '|-' ) {
# parent
my $str = "foo\n";
print {*STDERR} "parent [1]: ", pp($str), "\n";
print {*STDOUT} $str;
my $line = <$pty>;
print {*STDERR} "parent [2]: ", pp($line), "\n";
} else {
# child
while (<>) {
print {*STDERR} "child [1]: ", pp($_), "\n";
s/foo/bar/;
print {*STDERR} "child [2]: ", pp($_), "\n";
print $_;
} ## end while (<>)
exit;
} ## end else [ if ( my $pid = open *STDOUT...)]
The output I get is:
parent [1]: "foo\n"
child [1]: "foo\n"
child [2]: "bar\n"
parent [2]: "bar\r\n"
But on the last line I expected to receive "bar\n". Also, I'm running Perl under Linux, so shouldn't this LF to CRLF nonsense be a non-issue?
答案1
得分: 6
\r
和 \n
是"控制字符"。 "控制字符" 控制什么?是控制打字机的。嗯,以前是这样的。
TTYs 早于计算机,可以追溯到电报。TTY 代表电传打字机;它实际上是一种可以打印输出的打字机。由于它是一台打字机,需要告诉它将打印头(carriage)滑动(返回)到页面的第一列,然后将纸向下移动到下一行。\r\n
。
现在这个功能已经内置到 tty 协议中。尽管技术已经发展,但它仍然像与打字机通信一样工作。
另请参阅 script(1)输出中为什么换行是 CR + LF(dos 格式)?。
英文:
\r
and \n
are "control characters". What are "control characters" controlling? A typewriter. Well, it used to.
TTYs pre-date computers, going back to telegraphs. TTY stands for teletype; literally a typewriter that types the output. As it was a typewriter, it needed to be told to slide (return) the print head (carriage) back to the first column of the page, and then advance the paper to the next line. \r\n
.
Now that's baked into the tty protocol. Even though technology has moved on, it's still acting like it's talking to a typewriter.
See also Why in the output of script (1) the newline is CR + LF (dos-style)?
答案2
得分: 6
根据用户Schwern所指出,问题是由TTY本身引起的。
我通过在TTY上使用原始模式来解决了这个问题。
$pty->slave->set_raw();
$pty->set_raw();
英文:
As indicated by the user Schwern, the problem was caused by the TTY itself.
I solved it by using the raw mode on the TTY.
$pty->slave->set_raw();
$pty->set_raw();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论