Perl6 Tutorial

The -n option changes the behavior of the program: it executes the code once for every line of the file. So uppercase and print every line of /path/to/file.txt you can type:

  perl6 -ne '.uc.say' /path/to/file.txt

The -p option is just like -n except that it will automatically print $_. So another way we could uppercase a file would be:

  perl6 -pe '$_ = .uc' /path/to/file.txt

Or two shorter versions that do the same thing:

  perl6 -pe '.=uc' /path/to/file.txt
  perl6 -pe .=uc /path/to/file.txt

In the second example we were able to completely remove the surrounding single quotes. This is a rare scenario, but in the event your one liner has no spaces and no sigils or quotes in it, you can usually remove the outer quotes.

The -n and -p options are really useful. There are lots of example one-liners that use them in this book.

The final thing you should know is how to load a module. This is really powerful as you can extend Perl 6’s capabilities by importing external libraries. The -M switch stands for load module:

  perl6 -M URI::Encode -e 'say uri_encode("example.com/10 ways to crush it with Perl 6")'

This: -M URI::Encode loads the URI::Encode module, which exports the uri_encode subroutine. You can use -M more than once if you want to load more than one module:

  perl6 -M URI::Encode -M URI -e '<your code here>'

What if you have a local module, that is not installed yet? Easy, just pass use the -I switch to include the directory:

  perl6 -I lib -M URI::Encode -e '<your code here>'

Now Perl 6 will search for URI::Encode in lib as well as the standard install locations.

To get a list of Perl 6 command line switches, use the -h option for help:

  perl6 -h

Perl6 Oneliners

Perl6: Print n-grams of a string

  perl6 -e 'my $n=2; say "banana".comb.rotor($n,$n-1)>>.join()'

Perl6: Print unique n-grams

  perl6 -e 'my $n=2; say "banana".comb.rotor($n,$n-1)>>.join().Set.sort'

Perl6: Print occurrence counts of n-grams

  perl6 -e 'my $n=2; say "banana".comb.rotor($n,$n-1)>>.join().Bag.sort.join("\n")'

Perl6: Print occurrence counts of words (1-grams)

  perl6 -e 'say lines[0].words.join().Bag.sort.join("\n")' example.txt

Perl6: Print Dice similarity coefficient based on sets of 1-grams

  perl6 -e 'my $a="banana".comb;my $b="anna".comb;say ($a (&) $b)/($a.Set + $b.Set)'

Perl6: Print Jaccard similarity coefficient based on 1-grams

  perl6 -e 'my $a="banana".comb;my $b="anna".comb;say ($a (&) $b) / ($a (|) $b)'

Double space a file

  perl6 -pe '$_ ~= "\n"' example.txt

N-space a file (e.g. quadruple space)

  perl6 -pe '$_ ~= "\n" x 4' example.txt

Add a blank line before every line

  perl6 -pe 'say ""' example.txt

Remove all blank lines

perl6 -ne '.say if /\S/' example.txtperl6 -ne '.say if .chars' example.txt

Remove all consecutive blank lines, leaving just one

  perl6 -e '$*ARGFILES.slurp.subst(/\n+/, "\n\n", :g).say' example.txt

ROT 13 a file

  perl6 -pe 'tr/A..Za..z/N..ZA..Mn..za..m/' example.txt

Base64 encode a string

  perl6 -MMIME::Base64 -ne 'print MIME::Base64.encode-str($_)' example.txt

Base64 decode a string

  perl6 -MMIME::Base64 -ne 'print MIME::Base64.decode-str($_)' base64.txt

URL-escape a string

  perl6 -MURI::Encode -le 'say uri_encode($string)'

URL-unescape a string

  perl6 -MURI::Encode -le 'say uri_decode($string)'

HTML-encode a string

  perl6 -MHTML::Entity -e 'print encode-entities($string)'

HTML-decode a string

  perl6 -MHTML::Entity -e 'print decode-entities($string)'

Convert all text to uppercase

perl6 -pe '.=uc' example.txtperl6 -ne 'say .uc' example.txt

Convert all text to lowercase

  perl6 -pe '.=lc' example.txtperl6 -ne 'say .lc' example.txt

Uppercase only the first word of each line

  perl6 -ne 'say s/(\w+){}/{$0.uc}/' example.txt

Invert the letter case

perl6 -pe 'tr/a..zA..Z/A..Za..z/' example.txtperl6 -ne 'say tr/a..zA..Z/A..Za..z/.after' example.txt

Camel case each line

  perl6 -ne 'say .wordcase' example.txt

Strip leading whitespace (spaces, tabs) from the beginning of each line

  perl6 -ne 'say .trim-leading' example.txt

Strip trailing whitespace (space, tabs) from the end of each line

  perl6 -ne 'say .trim-trailing' example.txt

Strip whitespace from the beginning and end of each line

  perl6 -ne 'say .trim' example.txt

Convert UNIX newlines to DOS/Windows newlines

  perl6 -ne 'print .subst(/\n/, "\r\n")' example.txt

Convert DOS/Windows newlines to UNIX newlines

  perl6 -ne 'print .subst(/\r\n/, "\n")' example.txt

Find and replace all instances of “ut” with “foo” on each line

  perl6 -pe 's:g/ut/foo/' example.txt

Find and replace all instances of “ut” with “foo” on each line that contains “lorem”

  perl6 -pe 's:g/ut/foo/ if /Lorem/' example.txt

Convert a file to JSON

  perl6 -M JSON::Tiny -e 'say to-json(lines)' example.txt

Pick 5 random words from each line of a file

  perl6 -ne 'say .words.pick(5)' example.txt

Print the first line of a file (emulate head -1)

  perl6 -ne '.say;exit' example.txtperl6 -e 'lines[0].say' example.txt
  perl6 -e 'lines.shift.say' example.txt

Print the first 10 lines of a file (emulate head -10)

  perl6 -pe 'exit if ++$ > 10' example.txtperl6 -ne '.say if ++$ < 11' example.txt

Print the last line of a file (emulate tail -1)

  perl6 -e 'lines.pop.say' example.txt

Print the last 5 lines of a file (emulate tail -5)

  perl6 -e '.say for lines[*-5..*]' example.txt

Print only lines that contain vowels

  perl6 -ne '/<[aeiou]>/ && .print' example.txt

Print lines that contain all vowels

perl6 -ne '.say if .comb (>=) <a e i o u>' example.txtperl6 -ne '.say if .comb ⊇ <a e i o u>' example.txt

Print lines that are 80 chars or longer

perl6 -ne '.print if .chars >= 80' example.txtperl6 -ne '.chars >= 80 && .print' example.txt

Print only line 2

  perl6 -ne '.print if ++$ == 2' example.txt

Print all lines except line 2

  perl6 -pe 'next if ++$ == 2' example.txt

Print all lines 1 to 3

  perl6 -ne '.print if (1..3).any == ++$' example.txt

Print all lines between two regexes (including lines that match regex)

  perl6 -ne '.print if /^Lorem/../laborum\.$/' example.txt

Print the length of the longest line

  perl6 -e 'say lines.max.chars' example.txtperl6 -ne 'state $l=0; $l = .chars if .chars > $l;END { $l.say }' example.txt

Print the longest line

  perl6 -e 'say lines.max' example.txtperl6 -e 'my $l=""; for (lines) {$l = $_ if .chars > $l.chars};END { $l.say }' example.txt

Print all lines that contain a number

  perl6 -ne '.say if /\d/' example.txtperl6 -e '.say for lines.grep(/\d/)' example.txt
  perl6 -ne '/\d/ && .say' example.txt
  perl6 -pe 'next if ! $_.match(/\d/)' example.txt

Find all lines that contain only a number

  perl6 -ne '.say if /^\d+$/' example.txtperl6 -e '.say for lines.grep(/^\d+$/)' example.txt
  perl6 -ne '/^\d+$/ && .say' example.txt
  perl6 -pe 'next if ! $_.match(/^\d+$/)' example.txt

Print every even line

  perl6 -ne '.say if ++$ %% 2' example.txt

Print every odd line

  perl6 -ne '.say if ++$ !%% 2' example.txt

Print all lines that repeat

  perl6 -ne 'state %l;.say if ++%l{$_}==2' example.txt

Print unique lines

  perl6 -ne 'state %l;.say if ++%l{$_}==1' example.txt

Print the first field (word) of every line (emulate cut -f 1 -d ’ ’)

  perl6 -ne '.words[0].say' example.txt

Print overlap coefficient based on 1-grams

  perl6 -e 'my $a="banana".comb;my $b="anna".comb;say ($a (&) $b)/($a.Set.elems,$b.Set.elems).min'

Print cosine similarity based on 1-grams

  perl6 -e 'my $a="banana".comb;my $b="anna".comb;say ($a (&) $b)/($a.Set.elems.sqrt*$b.Set.elems.sqrt)'

Build an index of characters within a string and print it

  perl6 -e 'say {}.push: %("banana".comb.pairs).invert'

Build an index of words within a line and print it

  perl6 -e '({}.push: %(lines[0].words.pairs).invert).sort.join("\n").say' example.txt

Check if a number is a prime

  perl6 -e 'say "7 is prime" if 7.is-prime'

Print the sum of all the fields on a line

  perl6 -ne 'say [+] .split("\t")'

Print the sum of all the fields on all lines

  perl6 -e 'say [+] lines.split("\t")'

Shuffle all fields on a line

  perl6 -ne '.split("\t").pick(*).join("\t").say'

Find the lexically minimum element on a line

  perl6 -ne '.split("\t").min.say'

Find the lexically minimum element over all the lines

  perl6 -e 'lines.split("\t").min.say'

Find the lexically maximum element on a line

  perl6 -ne '.split("\t").max.say'

Find the lexically maximum element over all the lines

  perl6 -e 'lines.split("\t").max.say'

Find the numerically minimum element on a line

  perl6 -ne '.split("\t")».Numeric.min.say'

Find the numerically maximum element on a line

  perl6 -ne '.split("\t")».Numeric.max.say'

Replace each field with its absolute value

  perl6 -ne '.split("\t").map(*.abs).join("\t").say'

Find the total number of letters on each line

  perl6 -ne '.chars.say' example.txt

Find the total number of words on each line

  perl6 -ne '.words.elems.say' example.txt

Find the total number of elements on each line, split on a comma

  perl6 -ne '.split(",").elems.say' example.txt

Find the total number of fields (words) on all lines

  perl6 -e 'say lines.split("\t").elems' #fields
  perl6 -e 'say lines.words.elems' example.txt #words

Print the total number of fields that match a pattern

  perl6 -e 'say lines.split("\t").comb(/pattern/).elems' #fields
  perl6 -e 'say lines.words.comb(/pattern/).elems' #words

Print the total number of lines that match a pattern

  perl6 -e 'say lines.grep(/in/).elems'

Print the number PI to n decimal places (e.g. 10)

  perl6 -e 'say pi.fmt("%.10f");'

Print the number PI to 15 decimal places

  perl6 -e 'say π'

Print the number E to n decimal places (e.g. 10)

  perl6 -e 'say e.fmt("%.10f");'

Print the number E to 15 decimal places

  perl6 -e 'say e'

Print UNIX time (seconds since Jan 1, 1970, 00:00:00 UTC)

  perl6 -e 'say time'

Print GMT (Greenwich Mean Time) and local computer time

  perl6 -MDateTime::TimeZone -e 'say to-timezone("GMT",DateTime.now)'
  perl6 -e 'say DateTime.now'

Print local computer time in H:M:S format

  perl6 -e 'say DateTime.now.map({$_.hour, $_.minute,
      $_.second.round}).join(":")'

Print yesterday’s date

  perl6 -e 'say DateTime.now.earlier(:1day)'

Print date 14 months, 9 days and 7 seconds ago

  perl6 -e 'say DateTime.now.earlier(:14months).earlier(:9days).earlier(:7seconds)'

Prepend timestamps to stdout (GMT, localtime)

  tail -f logfile | perl6 -MDateTime::TimeZone -ne 'say to-timezone("GMT",DateTime.now) ~ "\t$_"'
  tail -f logfile | perl6 -ne 'say DateTime.now ~ "\t$_"'

Calculate factorial of 5

  perl6 -e 'say [*] 1..5'

Calculate greatest common divisor

  perl6 -e 'say [gcd] @list_of_numbers'

Calculate GCM of numbers 20 and 35 using Euclid’s algorithm



Calculate least common multiple (LCM) of 20 and 35

  perl6 -e 'say 20 lcm 35'

Calculate LCM of 20 and 35 using Euclid’s algorithm: n*m/gcd(n,m)

  perl6 -e 'say 20 * 35 / (20 gcd 35)'

Generate 10 random numbers between 5 and 15 (excluding 15)

  perl6 -e '.say for (5..^15).roll(10)'

Find and print all permutations of a list

  perl6 -e 'say .join for [1..5].permutations'

Generate the power set

  perl6 -e '.say for <1 2 3>.combinations'

Convert an IP address to unsigned integer

  perl6 -e 'say :256["127.0.0.1".comb(/\d+/)]'
  perl6 -e 'say +":256[{q/127.0.0.1/.subst(:g,/\./,q/,/)}]"'
  perl6 -e 'say Buf.new(+«"127.0.0.1".split(".")).unpack("N")'

Convert an unsigned integer to an IP address

  perl6 -e 'say join ".", @(pack "N", 2130706433)'
  perl6 -e 'say join ".", map { ((2130706433+>(8*$_))+&0xFF) }, (3...0)'

Number all lines in a file

  perl6 -ne 'say "{++$} $_"' example.txt
  perl6 -ne 'say $*ARGFILES.lines.kv ~ " $_"' example.txt

Number only non-empty lines in a file

  perl6 -pe '$_ = "{++$} $_" if /\S/' example.txt

Number all lines but print line numbers only for non-empty lines

  perl6 -pe '$_ = $*ARGFILES.lines.kv ~ " $_" if /\S/' example.txt

Print the total number of lines in a file (emulate wc -l)

  perl6 -e 'say lines.elems' example.txt
  perl6 -e 'say lines.Int' example.txt
  perl6 -e 'lines.Int.say' example.txt

Print the number of non-empty lines in a file

  perl6 -e 'lines.grep(/\S/).elems.say' example.txt

Print the number of empty lines in a file

  perl6 -e 'lines.grep(/^\s*$/).elems.say' example.txt

Generate and print the alphabet

  perl6 -e '.say for "a".."z"'

Generate and print all the strings from “a” to “zz”

  perl6 -e '.say for "a".."zz"'

Convert a integer to hex

  perl6 -e 'say 255.base(16)'
  perl6 -e 'say sprintf("%x", 255)'

Print an int to hex translation table

  perl6 -e 'say sprintf("%3i => %2x", $_, $_) for 0..255'

Percent encode an integer

  perl6 -e 'say sprintf("%%%x", 255)'

Generate a random 10 a-z character string

  perl6 -e 'print roll 10, "a".."z"'
  perl6 -e 'print roll "a".."z": 10'

Generate a random 15 ASCII Character password

  perl6 -e 'print roll 15, "0".."z"'
  perl6 -e 'print roll "0".."z": 15'

Create a string of specific length

  perl6 -e 'print "a" x 50'

Generate and print an array of even numbers from 1 to 100

  perl6 -e '(1..100).grep(* %% 2).say'

Find the length of the string

  perl6 -e '"storm in a teacup".chars.say'

Find the number of elements in an array

  perl6 -e 'my @letters = "a".."z"; @letters.Int.say'