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
%-12sleft-aligns a name;%5.2fright-aligns a price to two decimals.%08.3fzero-pads;%x,%oand%bprint one value in three bases.sprintfreturns the string instead of printing — handy for building table rows.
Keywords and builtins used here
myprintprintfsprintfuse
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.
Step 2 of 3 in Strings, step 14 of 27 in Language basics.