Perl: Format String

By Xah Lee. Date: . Last updated: .

Format String

For formatting strings, you can use “sprintf”, which is like other language's “format”.

Or, you can use “printf”, which is equivalent to print sprintf(FORMAT, LIST).

use utf8;
# integer
printf '%d', 1234;  # [1234]
print "\n";

# padding by space
printf '%4d', 12;   # [  12]
print "\n";

# float. 2 integer, 4 decimal
printf '%2.4f', 3.123456789;  # [3.1235]
print "\n";

# string.
printf '%5s', 'cats';  # [ cats]
print "\n";
printf '%2s', 'cats';  # [cats]
print "\n";

printf ('%2d,%6d,%2.4f,%s', 1234, 5678, 3.1415926, 'cats');
# prints [1234,  5678,3.1416,cats]

Perl String