Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between printf, print, and sprintf in Perl

Tags:

perl

What is the specific usage of print, printf, and sprintf in Perl?

All three keywords are used for printing purposes, but can someone differentiate it briefly?

like image 354
parthi Avatar asked Apr 27 '16 06:04

parthi


3 Answers

Short:

See the manuals:

  • http://perldoc.perl.org/functions/print.html
  • http://perldoc.perl.org/functions/printf.html
  • http://perldoc.perl.org/functions/sprintf.html

Long:

print is the default output function. It does no formatting but may append a line break if Perl is called with -l:

print $foo;
print "Hello $world";
print $filehandle $something;

sprintf is a formatter and doesn't do any printing at all:

$result = sprintf('The %s is %d', 'answer', 42);

printf is the same as sprintf, but actually prints the result:

printf 'This is question %d on %s', 36882022, 'StackOverflow';

See the sprintf documentation for more details on valid placeholders/format strings.

Since 5.10, Perl also supports say which is basically a print plus an additional \n.

like image 189
Sebastian Avatar answered Sep 20 '22 21:09

Sebastian


print just outputs.

printf takes a formatting string like "%3f" and uses it to format the output.

sprintf is the same as printf except it doesn't actually output anything. It returns a formatted string.

like image 35
Dave Ross Avatar answered Sep 19 '22 21:09

Dave Ross


The others covered the main points, but one other important little fact is that you can pass a list to print, just like die. It can be convenient sometimes and is apparently more efficient than concatenation if you are starting with a list.

e.g.

sub log_with_timestamp {
  my $timestamp = get_timestamp();
  print $timestamp, ' ', @_, "\n";
}
like image 29
Nick P Avatar answered Sep 21 '22 21:09

Nick P