typestar

Formatting with sprintf in Perl

printf-style templates for columns, padding and number bases.

use strict;
use warnings;

my $item = "espresso";
my $price = 3.5;
my $qty = 12;

printf "%-12s \$%5.2f\n", $item, $price;
printf "%08.3f\n", 3.14159;
printf "hex %x, octal %o, binary %b\n", 255, 255, 255;

my $row = sprintf "| %-8s | %6.2f |", $item, $price * $qty;
print "$row\n";

How it works

  1. %-12s left-aligns a name; %5.2f right-aligns a price to two decimals.
  2. %08.3f zero-pads; %x, %o and %b print one value in three bases.
  3. sprintf returns the string instead of printing — handy for building table rows.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
282
Tokens
66
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 57 seconds.

Type this snippet

Step 2 of 3 in Strings, step 14 of 27 in Language basics.

← Previous Next →

Formatting with sprintf in other languages