Input, Output and the MAIN Sub

8.1 Input

my $name = prompt 'What is your name? ';    # read a line from STDIN with a prompt
say "Hello, $name";
my $line = $*IN.get;                         # read one line
for $*IN.lines -> $l { say $l.uc }           # all lines
for lines() -> $l { }                        # files named in @*ARGS, or STDIN
my $all = slurp;                             # read everything from STDIN/ARGFILES

8.2 The MAIN Subroutine (Automatic CLI)

Multi MAIN gives subcommands:

%*SUB-MAIN-OPTS customizes parsing (e.g., :named-anywhere).

#!/usr/bin/env raku
#| Count words in a file
sub MAIN(
    Str $file where *.IO.f,           #= input file (must exist)
    Int :$top = 10,                    #= number of words to show
    Bool :$ignore-case,                #= case-insensitive counting
    *@extra,                           #= extra args
) {
    my $text = $file.IO.slurp;
    $text .= lc if $ignore-case;
    my %count is Bag = $text.comb(/\w+/);
    for %count.sort(-*.value).head($top) -> (:$key, :$value) {
        printf "%-15s %5d\n", $key, $value;
    }
}
raku wc.raku --top=5 --ignore-case book.txt
raku wc.raku --help        # auto-generated usage from the signature and #= comments
multi MAIN('add', Str $task)          { say "Adding $task" }
multi MAIN('list', Bool :$all)        { say "Listing (all: $all)" }
multi MAIN('done', Int $id)           { say "Completing #$id" }
sub USAGE { say "Usage: todo add <task> | list [--all] | done <id>" }   # custom usage