Perl sprintf: How Do I Use sprintf In a Perl Script?

September 8, 2019

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 = %.2fn",$num);'

Perl sprintf() Example

Type the following at the shell prompt:

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

To store output to a string or variable called $result you need to use the sprintf().

$result = sprintf("%.2f", $num); 
$now=sprintf("Today is ".`date`);
print "$resultn";
print "$nown";

Recommend readings:

  1. See perl sprintf() documentation for supported conversions, format parameter, flags etc.

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Article Tags:
Article Categories:
How To

Comments are closed.