枚举

在 Raku 中,枚举(enum)类型比其他语言复杂得多,详细信息可在此处的类型描述中找到。

这个简短的文档将给出一个简单的使用示例,就像在 C 语言中一样。

假设我们有一个需要写入各种目录的程序; 我们想要一个函数,给定一个目录名,测试它(1)是否存在(2)它是否可以被该程序的用户写入; 这意味着从用户的角度来看有三种可能的状态:要么你可以写(CanWrite),要么没有目录(NoDir)或者目录存在,但你不能写(NoWrite)。 测试结果将决定程序接下来要采取的操作。

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