perl.gg

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:

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:

Find the longest line:

Count non-empty lines:

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.