LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 2616 min read

String Formatting (sprintf)

Master sprintf and printf format specifiers to pad numbers, align columns, and build clean formatted output.

Introduction

Concatenating strings with dots gets messy fast, especially when you need columns to line up or numbers to show a fixed number of decimal places. Perl inherits printf-style formatting from C, giving you precise control over how values are rendered with sprintf and printf.

What You Will Learn
  • The difference between printf and sprintf.
  • The most useful format specifiers: %s, %d, %f, %x.
  • How to control width, alignment, and decimal precision.
  • How to build a clean, aligned table of output.

Why Formatting Matters

Reports, logs, and command-line tools are far easier to read when columns line up and numbers are shown consistently - for example, always with two decimal places for currency. sprintf and printf let you specify exactly how each value should be rendered, rather than relying on however Perl happens to stringify it.

printf vs sprintf

printf formats a string and immediately prints it (to STDOUT by default, or to a given filehandle). sprintf formats a string using the exact same rules but returns the result instead of printing it, so you can store it, pass it around, or build it up before deciding what to do with it.

use strict;
use warnings;
my $name = 'Alice';
my $score = 92.5;
printf "%-10s %6.2f%%\n", $name, $score;
my $line = sprintf("%-10s %6.2f%%", $name, $score);
print "$line\n";
Output

Click Run to see what this code prints.

Basic Format Specifiers

Every specifier starts with % and ends with a letter describing the type of value. Here are the ones you will use most often.

SpecifierMeaning
%sString
%dSigned decimal integer
%fFloating-point number
%xHexadecimal (lowercase)
%oOctal
%eScientific notation
%%A literal percent sign

Width and Alignment

Putting a number between the % and the letter sets a minimum field width. By default values are right-aligned; adding a minus sign left-aligns them instead - the key trick for lining up readable columns.

use strict;
use warnings;
printf "[%10s]\n", 'right';
printf "[%-10s]\n", 'left';
Output

Click Run to see what this code prints.

Precision for Floating-Point Numbers

For %f, a value after a dot controls how many digits appear after the decimal point, regardless of how many digits the original number had.

use strict;
use warnings;
printf "%.2f\n", 3.14159;
printf "%.0f\n", 3.9;
printf "%8.2f\n", 7.5;
Output

Click Run to see what this code prints.

Padding Numbers with Zeros

Putting a leading 0 before the width pads with zeros instead of spaces - handy for things like invoice numbers, timestamps, or fixed-width IDs.

use strict;
use warnings;
printf "%05d\n", 42;
printf "%+d\n", 7;
printf "%x\n", 255;
Output

Click Run to see what this code prints.

Building a Formatted Table

Combining width, alignment, and precision lets you build clean, aligned reports directly from a data structure - no manual spacing required.

use strict;
use warnings;
my @students = (
['Alice', 92.5],
['Bob', 78.333],
['Carlos', 85.0],
);
printf "%-10s %8s\n", 'Name', 'Score';
printf "%-10s %8s\n", '-' x 10, '-' x 8;
for my $row (@students) {
my ($name, $score) = @$row;
printf "%-10s %8.2f\n", $name, $score;
}
Output

Click Run to see what this code prints.

Common Mistakes

Avoid These Mistakes
  • Using %d for a value that might be a non-integer or a string - it silently truncates or prints 0.
  • Forgetting to double %% when you actually want a literal percent sign in the output.
  • Assuming sprintf prints something - it only returns a string, it does not print anything by itself.
  • Mismatching the number of specifiers and arguments, which leads to warnings or missing values.
  • Hardcoding column widths that break as soon as real data is longer than your test data.

Best Practices

  • Use sprintf when you need to store or further manipulate the formatted string; use printf when you just want to display it.
  • Always specify precision for currency and other decimal values (e.g. %.2f) so output is consistent.
  • Left-align text columns (%-Ns) and right-align numeric columns (%Nd) for readable tables.
  • Use a header row plus a separator row (built with the x repetition operator) for quick, clean report headers.
  • Prefer named intermediate variables over deeply nested sprintf calls for readability.

Frequently Asked Questions

Perl attempts a numeric conversion; a non-numeric string becomes 0, often with a warning under use warnings.

Yes, using positional specifiers like %1$s lets you reference the same argument more than once in one format string.

Yes - printf $filehandle "format", @args prints to a given filehandle instead of STDOUT.

Key Takeaways

  • printf prints formatted output directly; sprintf returns it as a string.
  • Common specifiers include %s, %d, %f, %x, and %%.
  • A minus sign before the width left-aligns; a leading zero zero-pads.
  • Precision after a dot (e.g. %.2f) controls decimal places for floats.
  • Combining width, alignment, and precision is the standard way to build clean report tables.

Summary

sprintf and printf give Perl precise, C-style control over how values are displayed, from simple padding to fully aligned report tables. With formatting under your belt, the next step is sorting data - one of the most common things you will do with lists and hashes.

Next Lesson →

Sorting Data