"Perl for Perl Newbies" - Part 4The sprintf functionSupported Conversions

2.1. Supported Conversions

Here are some of the supported conversions:

%% An actual percent sign
%c A character with the given ASCII number
%s A string
%d A signed integer, in decimal (also %i)
%o An integer in octal
%x An integer in hexadecimal. (use %X for uppercase hex)
%e A floating point number, in scientific notation.
%f A float in fixed decimal notation.
%b An integer in binary

Here are some examples:

#!/usr/bin/perl

use strict;
use warnings;

print sprintf("There is %i%% of alcohol in this beverage\n", 27);
print sprintf("%s%s\n", "This string", " ends here.");
print sprintf("650 in hex is 0x%x\n", 650);
print sprintf("650 in binary is 0b%b\n", 650);
print sprintf("3.2 + 1.6 == %f\n", 3.2+1.6);

And their output is:

There is 27% of alcohol in this beverage
This string ends here.
650 in hex is 0x28a
650 in binary is 0b1010001010
3.2 + 1.6 == 4.800000

Written by Shlomi Fish