Perl | sprintf() Function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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";

chevron_right


Output:

        Geeks
Geeks        


Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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";

chevron_right


Output:

007
123
0123


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.