3 ms·
In Perl, "\n" has a similar kind of platform-specific behavior like it does in some other languages (such as C). Its output is more or less defined as "whatever
by adrianmonk 7y ago
In Perl, "\n" has a similar kind of platform-specific behavior like it does in some other languages (such as C). Its output is more or less defined as "whatever is appropriate on this type of machine". It's useful for printing for the console or writing to a text file that will be used on the local machine, but not for everything.
If you're building a message to go on the wire as part of a protocol that needs certain specific characters, and if you're trying to write portable code, then you shouldn't use "\n" (or "\r").
This is actually covered in the "perldoc perlop" documentation under the "Quote and Quote-like Operators" section (available at https://perldoc.perl.org/perlop.html#Quote-Like-Operators https://perldoc.perl.org/perlop.html#Quote-Like-Operators):
> All systems use the virtual "\n" to represent a line terminator, called a "newline". There is no such thing as an unvarying, physical newline character. It is only an illusion that the operating system, device drivers, C libraries, and Perl all conspire to preserve. Not all systems read "\r" as ASCII CR and "\n" as ASCII LF. For example, on the ancient Macs (pre-MacOS X) of yesteryear, these used to be reversed, and on systems without a line terminator, printing "\n" might emit no actual data. In general, use "\n" when you mean a "newline" for your system, but use the literal ASCII when you need an exact character. For example, most networking protocols expect and prefer a CR+LF ("\015\012" or "\cM\cJ" ) for line terminators, and although they often accept just "\012" , they seldom tolerate just "\015" . If you get in the habit of using "\n" for networking, you may be burned some day.
So, arguably it is a bug to write it that way, but not exactly a fault of the language since it is providing a facility to do something useful and also explicitly warning you against using it for something else.
One way to think of "\n" is that it's similar to localized strings. In both cases, you have a need to let the system render something differently depending on context (platform or user location/language/etc., respectively). It's helpful to have that abstracted away, but you should realize that magic is happening and that you generally shouldn't use it for machine-to-machine communication.