Open In App

Perl | sprintf() Function

Improve
Improve
Like Article
Like
Save
Share
Report

sprintf() function in Perl uses Format provided by the user to return the formatted string with the use of the values in the list. This function is identical to printf but it returns the formatted string instead of printing it.

Syntax: sprintf Format, List

Returns: a formatted scalar string

Example 1:




#!/usr/bin/perl -w
  
# Formatting the string using sprintf
$text1 = sprintf("%8s", 'Geeks');
$text2 = sprintf("%-8s", 'Geeks');
  
# Printing the formatted string
print "$text1\n$text2";


Output:

        Geeks
Geeks        


Example 2:




#!/usr/bin/perl -w
  
# Formatting the string using sprintf
$text1 = sprintf("%03d", '7');
$text2 = sprintf("%03d", '123');
$text3 = sprintf("%04d", '123');
  
# Printing the formatted string
print "$text1\n$text2\n$text3";


Output:

007
123
0123

Last Updated : 07 May, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads