Josh and I are finishing up Effective Perl Programming, 2nd Edition, and the last part to finish off is the item on Perl one-liners.
Besides going through writing a one liner, we want to list a bunch of them too. Want to get your name in the book? Give us some one-liners that you wrote yourself and a couple of sentences about what it does. Make sure you tell us how you'd like your name to appear in the book, too. :)
perl -MSome::Module -e 0
perl -E 'say foreach split ":", $ENV{PATH}' # Or other pathlike thing.
ack --text -l '\bv1.2.3\b' | xargs perl -pi -e 's/\bv1\.2\.3\b/v1.2.4/g'
Otherwise, it's mostly experiments; I prefer bash to a REPL.
~$ perl -MAcme::MetaSyntactic=donmartin -E 'say metaname'
KLINK
Or, if I need several alternatives to boring values like 'foo':
~$ perl -MAcme::MetaSyntactic=any -E 'say metaname for 1..10'
l5nas_parchan
The_Living_Daylights
sugar
TO
Nick
Neptune
Pigpenb romine
Kyrano
voyager
But usually I prefere the donmartin
theme
Still my favorite is:
perl -ple'$_=eval'
It's a pure REPL. It evaluates every line from stdin and outputs whatever they evaluate to. It has many uses, but most of the time it's "just" a very powerful calculator.
I find I use -a rather alot for snippets like the following:
dpkg -l | perl -lane 'print $F[1] if $F[1] =~
/ruby/'
It's still useful for alternative delimiters. Pretending dpkg used tabs for delimiters, I'd add the parameter
-F$'\t'
It also find it's really helpful to got a proper handle on quoting whether in my shell or in perl. Often in a one-liner I'm using qq{} in perl to avoid messing with my shell's own use of ' or ". Occasionally I use bash's $'\t' syntax which lets me say things like
perl -F$'\t'
. I often say the ugly but effective:
perl -le 'print "Cant'\''t get no satisfaction"'
I use the very, very short one-liner
perl -dea
which just opens up a fresh debugger. I like that "dea" is supposedly the Latin word for goddess. I gather other people like to have other cute words like -debugger. It's all rather arbitrary but works as long as the word starts with the letters 'de'.
Here’s a replacement for cat(1):
perl -please somefile.txt