=begin pod :kind("Language") :subkind("Language") :category("fundamental")

=TITLE Enumeration

=SUBTITLE An example using the enum type

The C<enum> type is much more complex in Raku than in some other languages,
and the details are found in L<its type description|/language/typesystem#enum>.

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
(C<CanWrite>), or there is no directory (C<NoDir>) or the directory exists, but
you cannot write (C<NoWrite>). The results of the test will determine what
actions the program takes next.

=begin code
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
=end code

=end pod

# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6
