Perl Programming/Keywords/printf

Previous: print Keywords Next: prototype

The printf keyword Edit

The printf function is equivalent to print FILEHANDLE sprintf(FORMAT, LIST). The only difference to print is that the output record separator, $\, is not appended. The parametres FORMAT and LIST are parsed as a single list, where fhe first argument is understood as the format information.

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

  printf FORMAT, LIST

Examples Edit

  The code
	$dotextension = ".pl";
	$filename = "assign" . $dotextension;
	$filename2 = "assign1" . $dotextension;
	print $filename . ", " . $filename2 . "\n";

	open(my $fh, "<", $filename) 
		or die "cannot open < " . $filename . ": $!";
	open(my $fh2, ">", $filename2) 
		or die "cannot open < " . $filename2 . ": $!";

	read $fh, $f, 1024;

	printf($fh2 "%s, ", $f);	# Writes contents into $filename2

returns the contents of the file "":,

See also Edit

Previous: print Keywords Next: prototype