Perl sprintf: How do I use sprintf in a perl script?
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:
- Understanding Bash fork() bomb ~ :(){ :|:& };:
- Linux: Find my IP address using Perl at a shell prompt
- FreeBSD install Perl language
- How do I install a Perl Module?
- Find out if shell command is aliased or not
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!
Tags: formatted string, perl printf, perl script, perl sprintf, sprintf function, unix perl ~ Last updated on: November 2, 2007



Recent Comments
Today ~ 17 Comments
Today ~ 2 Comments
Today ~ 37 Comments
Today ~ 46 Comments
Yesterday ~ 2 Comments