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

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

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

    1. enum DirStat <CanWrite NoDir NoWrite>;
    2. sub check-dir-status($dir --> DirStat) {
    3. if $dir.IO.d {
    4. # dir exists, can the program user write to it?
    5. my $f = "$dir/.tmp";
    6. spurt $f, "some text";
    7. CATCH {
    8. # unable to write for some reason
    9. return NoWrite;
    10. }
    11. # if we get here we must have successfully written to the dir
    12. unlink $f;
    13. return CanWrite;
    14. }
    15. # if we get here the dir must not exist
    16. return NoDir;
    17. }
    18. # test each of three directories by a non-root user
    19. my $dirs =
    20. '/tmp', # normally writable by any user
    21. '/', # writable only by root
    22. '~/tmp'; # a non-existent dir in the user's home dir
    23. for $dirs -> $dir {
    24. my $stat = check-dir-status $dir;
    25. say "status of dir '$dir': $stat";
    26. if $stat ~~ CanWrite {
    27. say " user can write to dir: $dir";
    28. }
    29. }
    30. # output
    31. # status of dir '/tmp': CanWrite
    32. # user can write to dir: /tmp
    33. # status of dir '/': NoWrite
    34. # status of dir '~/tmp': NoDir