Open In App

Use of print() and say() in Perl

Last Updated : 18 Jun, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Perl uses statements and expressions to evaluate the input provided by the user or given as Hardcoded Input in the code. This evaluated expression will not be shown to the programmer as it’s been evaluated in the compiler. To display this evaluated expression, Perl uses print() function and say() function. These functions can display anything passed to them as arguments.

print() operator –

print operator in Perl is used to print the values of the expressions in a List passed to it as an argument. Print operator prints whatever is passed to it as an argument whether it be a string, a number, a variable or anything. Double-quotes(“”) is used as a delimiter to this operator.

Syntax:

print "";

Example:




#!/usr/bin/perl -w 
    
# Defining a string 
$string1 = "Geeks For Geeks"
$string2 = "Welcomes you all";
  
print "$string1";
print "$string2";


Output:

Geeks For GeeksWelcomes you all

Above example, prints both the strings with the help of print function but both the strings are printed in the same line. To avoid this and print them in different lines, we need to use a ‘\n’ operator that changes the line whenever used.

Example:




#!/usr/bin/perl -w 
    
# Defining a string 
$string1 = "Geeks For Geeks"
$string2 = "Welcomes you all";
  
print "$string1\n";
print "$string2";


Output:

Geeks For Geeks
Welcomes you all

If we use Single Quotes instead of double quotes, then the print() function will not print the value of the variables or the escape characters used in the statement like ‘\n’, etc. These characters will be printed as it is and will not be evaluated.

Example:




#!/usr/bin/perl -w 
    
# Defining a string 
$string1 = 'Geeks For Geeks'
$string2 = 'Welcomes you all';
  
print '$string1\n';
print '$string2';


Output:

$string1\n$string2

say() function –

say() function in Perl works similar to the print() function but there’s a slight difference, say() function automatically adds a new line at the end of the statement, there is no need to add a newline character ‘\n’ for changing the line.

Example:




#!/usr/bin/perl -w 
use 5.010;
  
# Defining a string 
$string1 = "Geeks For Geeks"
$string2 = "Welcomes you all";
  
# say() function to print
say("$string1");
say("$string2");


Output:

Geeks For Geeks
Welcomes you all

Here, we have used ‘use 5.010‘ to use the say() function because newer versions of Perl don’t support some functions of the older versions and hence, the older version is to be called to execute the say() function.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads