31、处理非数字加法的一种方法是先尝试进行加法运算,然后捕获异常。在 CATCH 块中可以使用 fail。实现子例程 add_two_things ( $first, $second ) 来处理非数字加法,并使用 my @items = < 2 2 3 two nine ten 1 37 0 0 > 进行测试。
sub add_two_things ( $first, $second ) {
CATCH {
when X::Str::Numeric {
fail q/One of the arguments wasn't a number/;
}
}
return $first + $second;
}
my @items = < 2 2 3 two nine ten 1 37 0 0 >;
for @items -> $first, $second {
my $sum = add_two_things( $first, $second );
put $sum.defined ?? "$first + $second = $sum" !! "You can't add $first and $second";
}
32、使用 val 检查每个参数,并与 Numeric 进行智能匹配。如果匹配不成功,使用 warn 进行提示。实现 sub add - two - things ( $first, $second ) ,并用 my @items = < 2 2 3 two nine ten 1 37 0 0 > 进行测试。同时,使用 quietly 忽略任何错误。
以下是实现代码:
```raku
sub add-two-things ( $first, $second ) {
CATCH {
when X::Str::Numeric {
fail q/One of the arguments wasn't a number/
}
}
for $first, $second {
warn "'$_' is not numeric" unless val($_) ~~ Numeric;
}
return $first + $second;
}
my @items = < 2 2 3 two nine ten 1 37 0 0 >;
for @items -> $first, $second {
my $sum = quietly add-two-things( $first, $second );
put $sum.defined ?? "$first + $second = $sum" !! "You can't add $first and $second";
}
33、逐一遍历命令行参数并分别进行测试:使用以下代码 for @*ARGS { unless .IO.e { put "'$_' does not exist"; next; }.put; put "readable" if .IO.r; put "writable" if .IO.w; put "executable" if .IO.x; } ,使用 given 重写代码并分析代码变化。
使用 given 重写的代码如下:
for @*ARGS -> $file {
given $file.IO {
unless .e {
put "'$file' does not exist";
next;
}
put $file;
put "readable" if .r;
put "writable" if .w;
put "executable" if .x;
}
}
代码变化分析:
使用 given 后,减少了多个 .IO 调用,但代码结构变得更复杂,逻辑嵌套增多。
34、编写一个程序,输出主目录,切换到一个子目录(使用第一个命令行参数),并输出当前工作目录。同时,尝试使用一个不存在的目录,程序应能处理该异常情况。
以下是几种实现方式的代码示例:
- 不使用 MAIN 子例程:
put "Home dir is $*HOME";
unless chdir $*HOME.IO.add: @*ARGS[0] {
die "Could not change directories: $!"
}
put "Current working dir is now $*CWD";
- 使用 MAIN 子例程:
sub MAIN (Str $subdir) {
put "Home dir is ", $*HOME;
unless chdir $*HOME.IO.add: @*ARGS[0] {
d

最低0.47元/天 解锁文章
8

被折叠的 条评论
为什么被折叠?



