Perl print() and say()

Perl print() function is one of the most commonly used function by the Perl users. It will print a string, a number, a variable or anything it gets as its arguments.

Syntax
print "";
Example

Let's see a simple example of Perl Print() function.

snippet
#!/usr/bin/perl
print "Welcome to rookienerd!!";
print "This is our Perl tutorial!!";
Output
Welcome to rookienerd!! This is our Perl tutorial!!

The above output prints both the sentences in the same line. To print them in different lines, we can use "\n" new line character in print function.

Print with '\n'

Example

The '\n' character is used to print a new line. It is used at the end of the print function.

snippet
#!/usr/bin/perl
print "Welcome to rookienerd!!\n";
print "This is our Perl tutorial!!\n";
Output
Welcome to rookienerd!! This is our Perl tutorial!!

Print with Variables

To print the variables value, you need to pass the variable in print function.

Example
snippet
#!/usr/bin/perl
$site = 'rookienerd';
print "Welcome to $site!!\n";
print "$site provides you all type of tutorials!!\n";
Output
Welcome to rookienerd!! rookienerd provides you all type of tutorials!!

Here, we have defined a variable $site. We have passed this variable in the string which prints its value in the output.

Print with Single and Double Quotes

Perl print function does not interpolate inside single quotes. It means it prints the characters inside single quote as it is. It neither evaluates the variable?s value nor does it interpret the escaping characters.

Example

When the above example runs inside a single quote, you will notice the following changes.

snippet
#!/usr/bin/perl
$site = 'rookienerd';
print 'Welcome to $site!!\n';
print '$site provides you all type of tutorials!!\n';
Output
Welcome to $site!! \n$site provides you all type of tutorials!!\n

In the output, variable $site is printed as it is. Its value is not evaluated. The new line character is also not interpreted.

Perl say()

The say() function is not supported by the older perl versions. It acts like print() function with only difference that it automatically adds a new line at the end without mentioning (\n).

Note
You need to mention the version in your script to use say() function. Without using version, you?ll get error in the output.
Syntax
snippet
say "";
Example

Let's see a simple example of perl say function.

snippet
#!/usr/bin/perl
use 5.010;
say "Welcome to rookienerd!!";
say "This is our Perl tutorial!!";
Output
Welcome to rookienerd!! This is our Perl tutorial!!

The above output prints both the sentences in different lines without using the new line character. And here we have used use 5.010 to support say function.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +