Perl Programming/Keywords/printf

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Previous: print Keywords Next: prototype

The printf keyword[edit | edit source]

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 | edit source]

  printf FILEHANDLE FORMAT, LIST
  printf FILEHANDLE
  printf FORMAT, LIST
  printf

Examples[edit | edit source]

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

	close($fh);
	close($fh2);
returns the contents of the file "assign.pl":
assign.pl, assign1.pl


See also[edit | edit source]

Previous: print Keywords Next: prototype