Butterfly Operator: One-Liner Magic Trick

By: w1ldc4rd-w1z4rd
[ BACK... ]

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:
perl -lne 'code before }{ code after'

# What Perl sees:
LINE: while (defined( = <ARGV>)) {
    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:

perl -lne '$sum += $_ }{print $sum'

Find the longest line:

perl -lne '$max = length if length > $max }{print $max'

Count non-empty lines:

perl -lne '$count++ if /\S/ }{print $count'

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