Why do Perl's and Python's output of print with "\n" differ?
Why do I need to put "\n" twice after "Content-Type: text/html" with Perl, but only once with Python? For example, the following Python script works:
#!/usr/bin/py开发者_StackOverflow中文版thon
print "Content-Type: text/html\n"
print "Hello World!"
But the following Perl script doesn't work (it gives a premature end of script headers error message):
#!/usr/bin/perl
print "Content-Type: text/html\n";
print "Hello World!";
Instead I need to add an extra "\n" to get it to work:
#!/usr/bin/perl
print "Content-Type: text/html\n\n";
print "Hello World!";
Because print in Python prints with a newline and print in Perl does not.
print "Hello world!"
in Python is equivalent to print "Hello world!\n"
in perl. Perl 6 has a say
command which does the same thing as Python's print, but sadly, Perl 6 has no stable implementations. In Perl 5.10 or later, you can use say
by putting use feature 'say'
in your script.
Perl's print
doesn't add a newline. Perl's say
does. These are equivalent:
# 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!";
I recommend not touching $\
; it can too easily affect code you don't want it to affect.
Python's print
outputs a newline automatically; Perl's doesn't (unless you set $\ = "\n"
). With newer Perl there's also say
, as mentioned by others.
精彩评论