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.
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:
xxxxxxxxxx
# What you type:
- 'code before }{ code after'
# What Perl sees:
: while (defined($_ = <ARGV>)) {
} # <-- The butterfly operator '}' closes this loop early
{ # <-- The '{' of the operator starts a new block
} # <-- 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.
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.
Sum numbers in a file:
xxxxxxxxxx
- '$sum += $_ }{print $sum'
Find the longest line:
xxxxxxxxxx
- '$max = length if length > $max }{print $max'
Count non-empty lines:
xxxxxxxxxx
- '$count++ if /\S/ }{print $count'
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.
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.
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.