xoi*_*oid 1 error-handling perl
我非常喜欢这种语法:
try_something() or warn "Cant do it";
Run Code Online (Sandbox Code Playgroud)
如何在之后添加更多命令or?
例如,它在这段代码中很有用:
foreach (@array)
{
m/regex/ or {warn "Does not match"; next;} # this syntax is wrong
...
}
Run Code Online (Sandbox Code Playgroud)
我找到的一种方法是
try_something() or eval {warn "Can't do it"; next;};
Run Code Online (Sandbox Code Playgroud)
但我认为这是个坏主意.
最好的答案:
do比...更好eval.do_smth() or warn("Does not match"), next;Nota bene:括号是必需的,warn因此next不会将其解析为其参数之一.我认为最终会很快变得难以理解,但你可以do:
foo() or do { bar(); baz(); };
Run Code Online (Sandbox Code Playgroud)
sub foo {
return $_[0] == 2;
}
for (1..3) {
print $_;
foo($_) or do { print " !foo\n"; next; };
print " foo!\n";
}
Run Code Online (Sandbox Code Playgroud)
对于你问题中的情况,我会用unless.
for (@array) {
unless (/regex/) {
warn "Does not match";
next;
}
...
}
Run Code Online (Sandbox Code Playgroud)
有时您可以使用逗号运算符.它评估它的左手参数,抛弃结果,评估右手参数并返回结果.适用于您的情况看起来像
for (@array) {
/regex/ or warn("Does not match"), next;
...
}
Run Code Online (Sandbox Code Playgroud)
请注意额外的括号.你必须更加小心括号并以这种方式分组.在使用这种技术时要明智:它会很快变得丑陋.
在下面的评论中,扎伊德建议道
warn('Does not match'), next unless /regex/;
Run Code Online (Sandbox Code Playgroud)
选择是一种风格问题.Perl是由语言学家创建的.自然语言允许我们以不同的方式表达相同的思想,这取决于我们想要强调的部分.在您的情况下,您想强调警告或模式匹配吗?将更重要的代码放在前面.
| 归档时间: |
|
| 查看次数: |
1012 次 |
| 最近记录: |