Perl sprintf Function

These sites are FOR SALE:,!
If you are interested, please use my Contact page.

The perl sprintf function returns a string formatted by the usual printf conventions of the C library function sprintf.

Instead of the printf function which prints the string to the current output filehandle or to the one specified by a filehandle, the sprintf function will return the formatted string in a scalar variable.

In this short free tutorial I'll show you a few examples about how to use this function to get a specific formatted string.

The syntax form of the Perl sprintf function is as follows:

$string = sprintf FORMAT, LIST

where the FORMAT is used to return a formatted string based on the LIST values.

Click Below to See the Best

Perl How-to Snippet Collection

and Save Hours of Surfing on Internet!

The sprintf function FORMAT allows you to use the following conversions:

Meaning, Example
a percent sign
a character with the given number

 my $string = sprintf '%c', 0x61;
 print "$string\n"; # it displays: a
a string

 my $string = sprintf '%s', "abcd";
 print "$string\n"; # it displays: abcd
a signed integer, in decimal

 my $string = sprintf '%d', 123415;
 print "$string\n"; # it displays: 123415
a synonym for %ld

 my $string = sprintf '%ld', 234151345;
 print "$string\n"; # it displays: 234151345
a synonym for %d

 my $string = sprintf '%i', -17324;
 print "$string\n"; # it displays: -17324
an unsigned integer, in decimal

 my $string = sprintf '%u', 2217324;
 print "$string\n"; # it displays: 2217324
a synonym for %lu

 my $string = sprintf '%U', 2217324334;
 print "$string\n"; # it displays: 2217324334
an unsigned integer, in octal

 my $string = sprintf '%o', 934522;
 print "$string\n"; # it displays: 3441172
a synonym for %lo
an unsigned integer, in hexadecimal

 my $string = sprintf '%x', 934522;
 print "$string\n"; # it displays: e427a
like %x, but using uppercase letters

 my $string = sprintf '%X', 934522;
 print "$string\n"; # it displays: E427A
a floating-point number in scientific notation

 my $string = sprintf '%e', -12.345;
 print "$string\n"; # it displays: -1.234500e+001
like %e, but using uppercase "E"

 my $string = sprintf '%E', -12.345;
 print "$string\n"; # it displays: -1.234500E+001
a floating-point number in fixed decimal notation

 my $string = sprintf '%f', -12.345;
 print "$string\n"; # it displays: -12.345000
a synonym for %f

 my $string = sprintf '%F', -12.345;
 print "$string\n"; # it displays: -12.345000
a floating-point number in %e or %f notation

 my $string = sprintf '%g', -1.234500E+1;
 print "$string\n"; # it displays: -12.345
like %g, but with an uppercase "E", if applicable
an unsigned integer, in binary

 my $string = sprintf '%b', 123;
 print "$string\n"; # it displays: 1111011
like %b, but using an uppercase "E", with the # flag
a pointer (outputs the Perl value’s address in hexadecimal)
special: *stores* the number of characters output so far into the next variable in the parameter list

You may specify several additional attributes between the % and the format letter in order to control the interpretation of the Perl sprintf function format:

Meaning, Example
By default sprintf will format the next unused argument in the list, but this parameter index, such as 2$, enables you to take the arguments out of order.

 my $string = sprintf '%2$d %1$d', 12, 34;
 print "$string\n"; # it displays: 34 12

 $string = sprintf '%3$d %d %1$d', 1, 2, 3;
 print "$string\n"; # it displays: 3 1 1
flags one
or more

prefix non-negative number with a space
prefix non-negative number with a plus sign
left-justify within the field
use zeros, not spaces, to right-justify
ensure the leading "0" for any octal,
prefix non-zero hexadecimal with "0x" or "0X",
prefix non-zero binary with "0b" or "0B"
vector flag It tells Perl to interpret the supplied string as a vector of integers, one for each character in the string.

Perl applies the format to each integer in turn, then joins the resulting string with a separator (a dot . by default).

If you put an asterisk * before the v you can override the string to use to separate the numbers:

 my $string = sprintf "%*vd", ":", "AB\x{100}";
 print "$string\n"; # it displays 65:66:256
(minimum) width Arguments are usually formatted to be as wide as required to display the given value, but you can override the width by putting a number here, or get the width from the next argument (with *):

 my $string = sprintf "%5s", "a";
 print "$string\n"; # it displays "    a"

 $string = sprintf "%*s", 5, "a";
 print "$string\n"; # it displays "    a"
precision, or maximum width You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a dot . followed by a number.

For floating-point formats (excepting g or G) this specifies how many places right of the decimal point to show:

 my $string = sprintf "%.2f", 123.4567;
 print "$string\n"; # it displays: 123.46

 $string = sprintf "%.5s", "language";
 print "$string\n"; # it displays: langu
size For numeric conversions, you can specify the size to interpret the number as using l, h, V, q, L or ll.


l - interpret integer as C type "long" or "unsigned long"
h - interpret integer as C type "short" or "unsigned short" or quads (typically 64-bit integers)
q, L or ll - interpret integer as C type "long long", "unsigned long long" or "quads" (typically 64-bit integers)

order of arguments You can use * to require additional arguments, these are consumed from the argument list in the order they appear in the format specification before the value to format:

 my $val = 1234.12345;
 my $string = sprintf "%*.*s", 9, 7, $val;
 print "$string\n"; # it displays: " 1234.12"

In the above example, 9 is uses for the width, 7 for the precision, and $val as the value to format.


Through these exercises you have the opportunity to try yourself to write some script code where you can use the Perl sprintf function. These exercises are completely covered in my Perl "Perl Scalar and String Functions - How To Tutorial" where I show you how to play with the Perl sprintf function in detail.
1. Use the Perl sprintf function to:
- limit the number of decimal places in your numbers (ex. print 1.333333333333 as 1.33)
- round a certain number of decimals (ex. 12.343789 as 12.344, 12.3 as 12.300)
- convert from decimal to hexadecimal
- convert from decimal to octal
- convert from decimal to binary
- pad a string with blanks on the left or right side
- pad a number on the left with zeroes
- expand variables in text strings
- format the localtime in a scalar variable (for example in the format yyyy-MM-dd hh:mm:ss)
2. Use the Perl sprintf function to replace notations like 4/25/10 (where the month appears first) by the notation 2010-25-04.
3. Give a short example where you use the /e modifier of the substitution operator s/// to run the Perl sprintf function inside a regular expression as pure Perl code.

A-N-Y-O-N-E Can Learn and Master Perl!
And That Includes YOU!

Check these how-to tutorial eBooks (PDF format):

Table of Contents:

A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays
    Array Size
    Array Length
Perl Hashes
Perl Statements
    Perl if
    Perl unless
    Perl switch
    Perl while
    Perl do-while
    Perl until
    Perl do-until
    Perl for
    Perl foreach
Built-in Perl Functions
    Functions by Category
        String Functions
        Regular Expressions and Pattern Matching
        List Functions
        Array Functions
        Hash Functions
        Miscellaneous Functions
    Functions in alphabetical order
        sprintf (more)

return from Perl sprintf function to Perl Basics

Would you like to create your own website like this one?
Hit the Alarm Clock!

Site Build It!