Perl logo

Perl Refreshments ⌘

Printing #2 - sprintf Examples

Example:

printf

As with pattern-matching and regexes, the printf function has special metacharacters to determine how to format strings. Buckle up ...

Another way of looking at them ...

IntegersFloating PointStrings
%b %B %d %h %o %p %u%e %E %f %g %G%c %s

There are others available for specifying numeric conversion, but we will leave that for another time (maybe).

Hold on, we're not quite done yet. Between the % sign and the formatting letter, we can also use the following attributes to control the format:

[ space ]Prefix a positive number with a space
+ Prefix a positive number with a plus sign
- Left-justify within the field
0 Use zeroes, not spaces, to right-justify
# Prefix nonzero octal with "0"; nonzero hex with "0x"; nonzero binary with "0b"
* Use value of next argument as field width
number$Use value of "number" at position "number"
*number$Use value of argument at position "number" as field width
numberMinimum field width (there is no maximum)
. numberPrecision: digits after the "dot" for floating-point numbers, maximum length for string, minimum length for integer

OK, I'm sure we all need some examples.

Here are some formatting examples of a floating point number:

my $numb=1234.567890;
print "\n\$numb: $numb\n";
my $numbFort = sprintf "-->% d<--",$numb;
print "\n$numbFort\n"; # prefix with space
$numbFort=sprintf "-->%%$numb<--\n",$numb;
print "\n$numbFort\n"; # prefix with percent sign
$numbFort=sprintf "-->%*s<--\n",12,$numb;
print "\n$numbFort\n"; # print in # 12 char. field
$numbFort=sprintf "-->%.5d<--\n",$numb;
print "\n$numbFort\n"; # pad with 0 for 5 char. integer

-30-