Butterfly Operator: One-Liner Magic Trick
In the realm of Perl wizardry, few tricks are as clever and compact as the “butterfly” operator. Discovered by Abigail in 1997, this curious construct }{ has become a favorite tool for crafting powerful one-liners.
What’s the Magic?
The butterfly operator exploits Perl’s -n and -p command-line options, which implicitly wrap your code in a while loop. By inserting }{ in your one-liner, you effectively create a makeshift END block. Here’s what’s happening behind the scenes:
# What you type:
-lne 'code before }{ code after'
perl
# What Perl sees:
while (defined($_ = <ARGV>)) {
LINE:
code before# <-- The butterfly operator '}' closes this loop early
} # <-- The '{' of the operator starts a new block
{
code after# <-- This closing brace is implicit }
This structure allows the first part to execute for each input line, while the second part runs once at the end - perfect for summaries and aggregations.
Why One-Liners Only?
The butterfly operator works exclusively in one-liners because it relies on the code generation of -n and -p options. In a regular Perl script, }{ would be a syntax error.
Practical Examples:
Sum numbers in a file:
-lne '$sum += $_ }{print $sum' perl
Find the longest line:
-lne '$max = length if length > $max }{print $max' perl
Count non-empty lines:
-lne '$count++ if /\S/ }{print $count' perl
The Names:
The term “butterfly” operator comes from the shape of the }{ symbol, which resembles a butterfly with its wings spread when rotated 90 degrees. This whimsical nickname showcases the Perl community’s fondness for creative and visual naming conventions.
Historical Context:
This technique emerged after The Perl Journal published an interview with Chip Salzenberg explaining Perl’s -n and -p options. Abigail, known for pushing Perl’s boundaries, likely saw an opportunity for creative exploitation of these features.
Conclusion:
The butterfly operator showcases Perl’s flexibility and the ingenuity of its community. It transforms a limitation of one-liners into a feature, allowing complex operations in incredibly compact code. Whether you use it daily or appreciate it as a curiosity, it stands as a testament to Perl’s capacity for surprise and creative expression.
Copyright ©️ 2024 perl.gg