Perl Programming/Keywords/sprintf

Previous: split Keywords Next: sqrt

The sprintf keyword

edit

The sprintf function returns a string formatted by the usual printf conventions of the C library function sprintf.

If the list is omitted, the contents of $_ is used as format information. To use the printf without a printf, a real filehandler like FH and not an indirect filehandler like $fh is required. In this case, if $_ contains formatting information, it will be replaced by an empty string and a warning will be emitted, if they are enabled. So, it's better to use print when the contents of $_ are to be used as formatting information.

print is simpler and less errorprone than printfǃ

Syntax

edit
  sprintf FORMAT, LIST

Examples

edit
  The code
	$a = 567;

	while ($a < 1000) {
		$result = sprintf("%08d", $a);
		$rounded = sprintf("%.5f", $a);
		print $result . ", " . $rounded . "\n";
		$a *= 1.1;
	}
returns the number with preceding zeros & with up to five zeros after the decimal digit:
00000567, 567.00000
00000623, 623.70000
00000686, 686.07000
00000754, 754.67700
00000830, 830.14470
00000913, 913.15917

See also

edit
Previous: split Keywords Next: sqrt