Say what, Perl?

Unlike in other languages, Perl's default print function doesn't print newlines by default. This is often desirable, such as in this case:

#!/usr/bin/env perl

use strict;
use warnings;

print("Please enter your name: ");
my $name = <STDIN>;

The resulting prompt will have the user type their name on the same line.

Please enter your name: Tousaka Rin

In situations where you want a newline, you use the standard \n:

print("Zettai Ryouiki FTW\n");
print("Tousakaaaaaa!\n");

This was the subject of ridicule from my Ruby development friends in the past, so in 2010 I presented a function that did the same thing. Recent Perl versions have an even shorter function name, with the say command. The following will print the same as the above:

say("Zettai Ryouiki FTW");
say("Tousakaaaaaaa!")

You can use this in your scripts today by requiring at least Perl 5.10, or explicitly enabling the feature:

use 5.010;
use feature qw(say);

Done, and done.


Imprint

This is one of about 5000 posts on Rubénerd. View the home page for the latest, or related posts also tagged with:

If you liked this post, feel free to buy me a coffee, leave me a comment on Twitter, or email me at weblog2017@rubenschade.com. Thanks :).