Perl sprintf: How Do I Use sprintf In a Perl Script?

How do I use sprintf() function in a perl script under Linux or UNIX?

Perl printf() function is used 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. 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.

ADVERTISEMENTS

Perl printf() Example

The following statement will round number to 2 digits after decimal point, enter:

perl -e '$num=53535.35353535;printf ("Result = %.2f\n",$num);'

Perl sprintf() Example

Type the following at the shell prompt:

perl -e '$num=53535.35353535;$result=sprintf("Result = %.2f\n",$num);print "$result"'

To store output to a string or variable called $result you need to use the sprintf().

#!/usr/bin/perl
$num=585858.64645;
$result = sprintf("%.2f", $num); 
$now=sprintf("Today is ".`date`);
print "$result\n";
print "$now\n";

Recommend readings:

  1. See perl sprintf() documentation for supported conversions, format parameter, flags etc.
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
3 comments… add one
  • Peko Apr 6, 2009 @ 14:53

    Hi Vivek nixCraft Wizard,
    Thanks for your work.

    I think there are two bugs.
    Shouldn’t “print” instructions be :
    print “$result\n”;
    print “$now\n”;

    instead of using double backslash ?
    /* that’s what work on my system *:

    — Peko

    • dg Jun 17, 2011 @ 17:42

      @Peko
      He probably tried to escape it so it showed up right on the website, but you are correct there should only be one backslash for the newline escape character.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.