Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

5. Input and Output > Formatted Output with printf

Formatted Output with printf

You may wish to have a little more control with your output than print provides. In fact, you may be accustomed to the formatted output of C’s printf function. Fear not! Perl provides a comparable operation with the same name.

The printf operator takes a format string followed by a list of things to print. The format[140] string is a fill-in-the-blanks template showing the desired form of the output:

printf "Hello, %s; your password expires in %d days!\n",
    $user, $days_to_die;

The format string holds a number of so-called conversions; each conversion begins with a percent sign (%) and ends with a letter. (As you’ll see in a moment, there may be significant extra characters between these two symbols.) There should be the same number of items in the following list as there are conversions; if these don’t match up, it won’t work correctly. In the example above, there are two items and two conversions, so the output might look something like this:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial