← Back to Perl Course | Chapter 3: Strings | Lesson 7 of 7

sprintf and printf

sprintf builds a formatted string, and printf prints it directly.

In this page:

  1. sprintf and printf

sprintf and printf

The format string contains conversion codes such as %s for strings, %d for integers, %f for floating-point numbers and %x for hexadecimal. You can add a width, a precision such as %.2f, a minus sign for left alignment and a 0 for zero padding. printf prints the formatted result, while sprintf returns it so you can store it.

Note: Write %% to print a literal percent sign.

Example: sprintf and printf

perl
use strict;
use warnings;

my $pi = 3.14159265;
printf "Pi to 2 places: %.2f\n", $pi;
printf "Integer from float: %d\n", 7.9;
printf "Padded: [%5d] [%-5d] [%05d]\n", 42, 42, 42;
printf "Strings: [%8s] [%-8s]\n", "right", "left";
printf "Hex: %x, Octal: %o, Binary: %b\n", 255, 8, 5;
printf "Percent: %d%%\n", 50;
my $row = sprintf("%-10s|%6.1f", "Total", 1234.567);
print "$row\n";
print "Scientific: ", sprintf("%.3e", 12345.678), "\n";

# Output:
# Pi to 2 places: 3.14
# Integer from float: 7
# Padded: [   42] [42   ] [00042]
# Strings: [   right] [left    ]
# Hex: ff, Octal: 10, Binary: 101
# Percent: 50%
# Total     |1234.6
# Scientific: 1.235e+04
Common Mistakes
  1. Providing fewer arguments than there are conversion codes
  2. Using %d with a fractional number and expecting rounding
  3. Forgetting that printf does not add a newline
Chapter Summary
  • %s string %d integer %f float
  • %.2f sets the precision
  • Width and flags align and pad
  • sprintf returns and printf prints
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.