Current Issue


Table of contents

CD-ROM

Sys Admin and The Perl Journal CD-ROM version 12.0

Version 12.0 delivers every issue of Sys Admin from 1992 through 2006 and every
issue of The Perl Journal from 1996-2002 in one convenient CD-ROM!

Order now!

Sys Admin Magazine > Archives > 2000 > 0006

Page artGetting It to Look the Way You Want
Randal L. Schwartz

For the most part, Perl programmers tend to use the nice standby print operator for output, or drift occasionally into the realm of formats to quickly lay out a look for a customized report. However, the often overlooked printf operator provides a nice amount of custom control to get those output strings to look exactly the way you want.

The printf operator takes a format string, and zero or more values. The format string drives the whole process. With a few exceptions, each percent % field in the format string matches up with one of the additional values, defining how the value will appear in the output. For example:

printf "my string %s has %d characters.\n", $str, length($str);

Here, the %s field calls for a string value, provided by $str. Similarly, the %d field calls for a decimal integer, provided by the length($str) computation. The parameters are evaluated in a list context, so we could have also used the following code to accomplish the same output:

@output = ($str, length($str)); printf "my string %s has %d characters.\n", @output;

This gets interesting if we don't know the length of @output, because we need a %-field for each element of @output, but since we set it up ourselves here, that's not a problem.

Besides %s for string, and %d for decimal integer, another common format is %f for floating point:

printf "he has $%f in his account\n", 3.5




MarketPlace

"Six Sigma" Certification
Villanova Six Sigma Certification 100% Online Program - Free Info.

Project Management-Online
Nation's Leading Online PMP Course From Villanova-Find Out More Now.

Automate Software Builds with Visual Build Pro
Easily create an automated, repeatable process for building and deploying software.

WinDev 12 - Powerful IDE
Develop 10 times faster ! ALM, IDE, .Net, RAD, 5GL, Database, 5GL, 64-bit, etc. Free Express version

Wanna see your ad here?