Skip to content

Commit d277ade

Browse files
committed
add new doc en an enum example
1 parent 2ac4c00 commit d277ade

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

doc/Language/enumeration.pod6

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
=begin pod :tag<perl6>
2+
3+
=TITLE Enumeration
4+
5+
=SUBTITLE Using the enum type
6+
7+
=head1 X<An example using the enum type|enum, example>
8+
9+
In Perl 6 the C<enum> type is much more complex than in some other languages, and the details
10+
are found in its type description here: L<enum|/language/typesystem#enum>.
11+
12+
This short document will give a simple example of its use similar to use in C-like languages.
13+
14+
Say we have a program that needs to write to various directories so we want a function that,
15+
given a directory name, tests it for (1) its existence and (2) whether it can be written to by
16+
the user of the program. The results of the test will determine what actions the program
17+
takes next.
18+
19+
=begin code
20+
# the directory will have one of these three statuses from the user's perspective:
21+
enum DirStat <CanWrite NoDir NoWrite>;
22+
sub check-dir-status($dir --> DirStat) {
23+
if $dir.IO.d {
24+
# dir exists, can the program user write to it?
25+
my $f = "$dir/.tmp";
26+
spurt $f, "some text";
27+
CATCH {
28+
# unable to write for some reason
29+
return NoWrite;
30+
}
31+
# if we get here we must have successfully written to the dir
32+
unlink $f;
33+
return CanWrite;
34+
}
35+
# if we get here the dir must not exist
36+
return NoDir;
37+
}
38+
39+
# test each of three directories by a non-root user
40+
my $dirs =
41+
'/tmp', # normally writeable by any user
42+
'/', # writeable only by root
43+
'~/tmp'; # a non-existent dir in the user's home dir
44+
for @dirs -> $dir {
45+
my $stat = check-dir-status $dir;
46+
say "status of dir '$dir': $stat";
47+
if $stat ~~ CanWrite {
48+
say " user can write to dir: $dir";
49+
}
50+
# output
51+
# status of dir '/tmp': CanWrite
52+
# user can write to dir: /tmp
53+
# status of dir '/': NoWrite
54+
# status of dir '~/tmp': NoDir
55+
=end code
56+
57+
=end pod
58+
59+
# vim: expandtab shiftwidth=4 ft=perl6

0 commit comments

Comments
 (0)