Avoid the "butterfly operator" with command-line options

TL;DR

When a giant chimes in, it’s impossible to avoid learning something.

In recent post JSONify a string I showed a little one-liner to… JSONify a string:

perl -MJSON::PP -pe '$x.=$_}{$_=encode_json([$x]);s/^\[|\]$//g' style.css

It uses the so-called “butterfly operator” (which is not a real operator, just a visual trick) to collect all the input in scalar $x, before using it to generate the encoded string.

Having written about it was indeed very fruitful.

Αριστοτέλης Παγκαλτζής took a look and had the kindness to share a simpler way to do this slurping from the command line:

tweet screenshot

So… I learned that option -0xxx allows setting the input separator $/ from the command line as an octal value, and that using 0777 is the conventional way to say just get everything.

Result: no need to use the butterfly operator any more, because when we set the input separator like this, the very first read action will take everything in one single sweep and we can use encode_json immediately.

In this case, then, the equivalent code (thanks to the -p option) becomes something like this:

local $/; # set "slurp" mode, like -0777 does
while (<>) {
    $_ = substr encode_json([$_]), 1, -1;
    print $_;  # print to currently selected filehandle
}

Brilliant!

Update: the equivalent code above was made more accurate thanks to Randal L. Schwartz’s comment below. I managed to put two inaccuracies in a single code fragment of four lines, not bad! 🙄


Comments? Octodon, , GitHub, Reddit, or drop me a line!