Enumeration
ErrorsCollection

Enumeration

An example using the enum type

The enum type is much more complex in Raku than in some other languages, and the details are found in its type description.

This short document will give a simple example of its use as is the usual practice in C-like languages.

Say we have a program that needs to write to various directories; we want a function that, given a directory name, tests it for (1) its existence and (2) whether it can be written to by the user of the program; this implies that there are three possible states from the user perspective: either you can write (CanWrite), or there is no directory (NoDir) or the directory exists, but you cannot write (NoWrite). The results of the test will determine what actions the program takes next.

enum DirStat <CanWrite NoDir NoWrite>;
sub check-dir-status($dir --> DirStat{
    if $dir.IO.d {
        # dir exists, can the program user write to it? 
        my $f = "$dir/.tmp";
        spurt $f"some text";
        CATCH {
            # unable to write for some reason 
            return NoWrite;
        }
        # if we get here we must have successfully written to the dir 
        unlink $f;
        return CanWrite;
    }
    # if we get here the dir must not exist 
    return NoDir;
}
 
# test each of three directories by a non-root user 
my @dirs = (
    '/tmp',  # normally writable by any user 
    '/',     # writable only by root 
    '~/tmp'  # a non-existent dir in the user's home dir 
);
for @dirs -> $dir {
    my $stat = check-dir-status $dir;
    say "status of dir '$dir': $stat";
    if $stat ~~ CanWrite {
        say "  user can write to dir: $dir";
    }
}
# output 
#   status of dir '/tmp': CanWrite 
#     user can write to dir: /tmp 
#   status of dir '/': NoWrite 
#   status of dir '~/tmp': NoDir