Welcome to Day 20 of the Perl 6 One-Liner Advent Calendar! So far, we created about 25 different one-liners, but never talked about the command-line options that the Rakudo Perl 6 compiler offers to us.
The first option to know when working with (Rakudo) Perl 6 is -e. It takes a string with your Perl 6 one-liner and executes it immediately.
For example, print the version of the current Perl 6 specification:
$ perl6 -e'$*PERL.version.say'
Be careful not to use the Perl 5.10+ styled capital -E, which does the same as -e but also activates features such as say. In Perl 6, the option is always lowercase.
This option repeats the code for each line of input data. This is quite handy when you want to process a file. For example, here’s a one-liner that adds up the values in a row and prints the sum:
$ perl6 -ne'say [+] .split(" ")' data.txt
If the data.txt file contains the following:
10 20 30 40
1 2 3 4
5 6 7 8
then the result of the one-liner is:
There’s no difference whether you use shell’s input redirection or not; the following line also works:
$ perl6 -ne'say [+] .split(" ")' < data.txt
Make sure you place the e option the last in the list (so, not perl6 -en'...') or split the options: perl6 -n -e'...'.
This option is similar to -n, but prints the topic variable after each iteration.
The following one-liner reverses the lines in the file and prints them to the console:
$ perl6 -npe'.=flip' data.txt
For the same input file, the result will look like this:
04 03 02 01
4 3 2 1
8 7 6 5
Notice that you have to update the $_ variable, so you type .=flip. If you only have .flip, you will reverse the string, but the result will not be used and the original line will be printed.
An equivalent program with .flip and with no -p will look like this:
$ perl6 -ne'.flip.say' data.txt
Let’s go through a few one-liners from the Perl One-Liners book and create one-liners in Perl 6.
Double-space a file
$ perl6 -npe's/$/\n/' text.txt
Remove all blank lines
$ perl6 -ne'.say if .chars' text.txt
Depending on how you define ‘blank’, you may want another one-liner that skips the lines containing whitespaces:
$ perl6 -ne'.say if /\S/' text.txt
Number all lines in a file
$ perl6 -ne'say ++$ ~ ". " ~ $_' text.txt
Convert all text to uppercase
$ perl6 -npe'.=uc' text.txt
Strip whitespace from the beginning and end of each line
$ perl6 -npe'.=trim' text.txt
Print the first line of a file
$ perl6 -ne'.say ; exit' text.txt
Print the first 10 lines of a file
$ perl6 -npe'exit if $++ == 10' text.txt
This time, a postfix ++ was applied to $.
I hope that was a useful journey today. See you tomorrow!