Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

Formatting Data with sprintf

The sprintf function takes the same arguments as printf (except for the optional filehandle, of course), but it returns the requested string instead of printing it. This is handy if you want to store a formatted string into a variable for later use, or if you want more control over the result than printf alone would provide:

my $date_tag = sprintf
  "%4d/%02d/%02d %2d:%02d:%02d",
  $yr, $mo, $da, $h, $m, $s;

In that example, $date_tag gets something like "2038/01/19 3:00:08". The format string (the first argument to sprintf) used a leading zero on some of the format number, which we didn’t mention when we talked about printf formats in Chapter 5. The leading zero on the format number means to use leading zeros as needed to make the number as wide as requested. Without a leading zero in the formats, the resulting date-and-time string would have unwanted leading spaces instead of zeros, like "2038/ 1/19 3: 0: 8".

Using sprintf with “Money Numbers”

One popular use for sprintf is when you want to format a number with a certain number of places after the decimal point, such as when you want to show an amount of money as 2.50 and not 2.5—and certainly not as 2.49997! That’s easy to accomplish with the "%.2f" format:

my $money = sprintf "%.2f", 2.49997;

The full implications of rounding are numerous and subtle, but, in most cases, you should keep numbers in memory with all of the available accuracy, rounding off only for output.

If you have a “money number” that may be ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page