Perl sprintf: Format Strings Guide

In Perl, the sprintf function is used to generate and return a formatted string. Its basic usage is as follows:

my $formatted_string = sprintf("格式化字符串", 参数1, 参数2, ...);

Among them:

  1. “A formatted string” is a string that includes a specific format, similar to the formatted strings in the printf function in C programming language.
  2. Parameters 1, 2, … are the values to be inserted into the formatted string.

For example, to format a number as a string with two decimal places, you can use the sprintf function like this:

my $num = 3.14159;
my $formatted_num = sprintf("%.2f", $num);
print $formatted_num;  # 输出:3.14

Apart from %f, the sprintf function also supports various formatting directives such as %d (integer), %s (string), %x (hexadecimal), %o (octal), etc. You can choose the appropriate formatting directive based on your specific needs.

bannerAds