How do I use sprintf() function in a perl script under Linux or UNIX?
Perl printf() function is used 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. 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
The following statement will round number to 2 digits after decimal point, enter:
perl -e '$num=53535.35353535;printf ("Result = %.2f\n",$num);'
Perl sprintf() Example
Type the following at the shell prompt:
perl -e '$num=53535.35353535;$result=sprintf("Result = %.2f\n",$num);print "$result"'
To store output to a string or variable called $result you need to use the sprintf().
#!/usr/bin/perl $num=585858.64645; $result = sprintf("%.2f", $num); $now=sprintf("Today is ".`date`); print "$result\n"; print "$now\n";
Recommend readings:
- See perl sprintf() documentation for supported conversions, format parameter, flags etc.
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop













{ 3 comments… read them below or add one }
Hi Vivek nixCraft Wizard,
Thanks for your work.
I think there are two bugs.
Shouldn’t “print” instructions be :
print “$result\n”;
print “$now\n”;
instead of using double backslash ?
/* that’s what work on my system *:
– Peko
@Peko
He probably tried to escape it so it showed up right on the website, but you are correct there should only be one backslash for the newline escape character.
@dg,
Thanks for the heads up.