About Linux FAQ

Browse More FAQs:

Perl sprintf: How do I use sprintf in a perl script?

Posted by Vivek on Wednesday March 14, 07 @10:17 am

Q. How do I use sprintf() function in a perl script under Linux or UNIX?

A. perl printf() function is use to format and print data on screen.

You need to use sprintf to print or store formatted data/string to a variable or to a string.

Also note that Perl does its own sprintf formatting--it emulates the C function sprintf, but it doesn't use it (except for floating-point numbers, and even then only the standard modifiers are allowed). As a result, any non-standard extensions in your local sprintf are not available from Perl.

perl printf() example

Following statement will round number to 2 digits after decimal point (type at shell prompt):
$ perl -e '$num=53535.35353535;printf ("Result = %.2f\n",$num);'

perl sprintf() example

Type following at shell prompt:

$ perl -e '$num=53535.35353535;$result=sprintf("Result = %.2f\\n",$num);print "$result"'

If you need to store output to a string / variable called $result you need to use sprintf(). Here is a small script to make you idea more clear:

#!/usr/bin/perl
$num=585858.64645;
$result = sprintf("%.2f", $num);
$now=sprintf("Today is ".`date`);
print "$result\\n";
print "$now\\n";

Note that variable $now and $result stores the formatted string. Refer this perl sprintf() documentation for supported conversions, format parameter, flags etc.

Subscribe to our free e-mail newsletter or RSS feed to get all updates. You can Email this page to a friend.

Related Linux / UNIX FAQ:

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Please do not use the comment form to ask for help / question. Ask your question on the excellent Linux tech support forum. Thank you very much for stopping by our site!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Tags: , , , , , ~ Last updated on: November 2, 2007

Copyright © 2006-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.