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";
No comments:
Post a Comment