String formatting in Perl allows developers to create structured and formatted output. It's an essential skill for presenting data in a readable and organized manner.
Perl offers several methods for string formatting. The most common are sprintf
and printf
functions.
The sprintf
function returns a formatted string without printing it. It's useful when you need to store the formatted string for later use.
my $formatted = sprintf("Name: %s, Age: %d", "John", 30);
print $formatted; # Output: Name: John, Age: 30
printf
is similar to sprintf
, but it prints the formatted string directly.
printf("Balance: $%.2f\n", 1234.5678); # Output: Balance: $1234.57
Format specifiers are placeholders used in formatting strings. They start with a percent sign (%) followed by a character that indicates the data type.
%s
- String%d
- Integer%f
- Float%x
- Hexadecimal%o
- OctalPerl's string formatting capabilities extend beyond basic placeholders. You can specify width, precision, and alignment.
printf("|%-10s|%10s|\n", "Left", "Right");
# Output: |Left | Right|
printf("Pi: %.*f\n", 3, 3.14159265);
# Output: Pi: 3.142
For more complex formatting needs, Perl provides the format
function. It's particularly useful for creating report-like output.
format STDOUT =
Name: @<<<<<<<<<<<<<< Age: @>>
$name, $age
.
$name = "Alice";
$age = 25;
write; # Outputs the formatted text
sprintf
when you need to store the formatted string.printf
for direct output to avoid unnecessary variable creation.Mastering string formatting in Perl enhances your ability to create clean, readable output. It's a crucial skill that complements other Perl String Functions and is often used in conjunction with Perl Regular Expressions for powerful text processing capabilities.