为什么使用"\n"的Perl和Python输出不同?

3
为什么在Perl中在“Content-Type: text/html”后面需要两次输入“\n”,而在Python中只需要一次?例如,以下Python脚本有效:
#!/usr/bin/python
print "Content-Type: text/html\n"
print "Hello World!"

但是下面的Perl脚本无法正常工作(它会返回一个“脚本头过早结束”的错误消息):
#!/usr/bin/perl
print "Content-Type: text/html\n";
print "Hello World!";

相反,我需要添加一个额外的“\n”才能使其正常工作:

#!/usr/bin/perl
print "Content-Type: text/html\n\n";
print "Hello World!";

-1:答案是“因为它们是不同的语言”。为什么要问呢?你怎么能明智地比较两种不同的语言呢?如果你要比较语言,为什么不问一下 Ruby、C++、C# 和 VB 呢? - S.Lott
3个回答

15
因为在Python中,使用print打印输出会自动换行,而在Perl中则不会。
在Python中,print "Hello world!"的效果等同于在Perl中写print "Hello world!\n"。Perl 6也有一个say命令,其功能与Python的print相同,但可惜的是,Perl 6没有稳定的实现版本。在Perl 5.10或更高版本中,您可以通过在脚本中加入use feature 'say'来使用say命令。

10

Perl的print不会添加换行符。而Perl的say会自动添加。以下两者等效:

# Python
print "Content-Type: text/html"
print ""
print "Hello World!"

# Perl
print "Content-Type: text/html\n";
print "\n";
print "Hello World!\n";

# Perl
local $\ = "\n";
print "Content-Type: text/html";
print "";
print "Hello World!";

# Perl
use 5.010;
say "Content-Type: text/html";
say "";
say "Hello World!";

我建议不要触碰$\;它很容易影响你不想影响的代码。


1

Python的print会自动输出一个换行符;Perl则不会(除非你设置$\ = "\n")。在更新的Perl中也有say,正如其他人所提到的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接