为什么要使用“do {} if”? Perl 中的块?
在浏览 CPAN 时,我在 this 中遇到了一段代码模块 难倒了我。
sub import {
for my $mod (keys %INC) {
do {
delete $INC{$mod};
$mod =~ s/\.pm$//; $mod =~ s/\//::/g;
delete_package($mod);
} if $mod =~ m/^SOAP/;
}
}
为什么作者要使用 do {} if
块而不是常规的 if
块?
While browsing CPAN, I came across a block of code in this module that stumped me.
sub import {
for my $mod (keys %INC) {
do {
delete $INC{$mod};
$mod =~ s/\.pm$//; $mod =~ s/\//::/g;
delete_package($mod);
} if $mod =~ m/^SOAP/;
}
}
Why would the author use a do {} if
block instead of a regular if
block?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为他们喜欢这样。没有什么真正的区别。 Perl 有十几种方法可以完成所有事情。语言就是这样。
Because they feel like it. There's no real difference. Perl has like a dozen ways to do everything. It's just the way the language is.
一个区别是
do { ... }
返回一个值,而 if 语句则不返回值(尽管请参阅下面的注释。)例如:
您可以使用三元运算符完成几乎相同的事情,尽管您无法对三元运算符的分支内的语句进行排序。
One difference is that
do { ... }
returns a value whereas an if statement doesn't (although see the comments below.)E.g.:
You can accomplish almost the same thing with the ternary operator, although you can't sequence statements inside the branches of the ternary operator.
对我来说,这似乎是一种强调
if
内部代码而不是if
条件本身的方法。To me, it seems like a way to emphasize the code inside the
if
more than theif
condition itself.作者想在最后使用if,但它必须在一个语句的末尾,数量不多。
do {}
是一个语句,因此可以工作。就我个人而言,我会使用 if 语句,但重点应该放在操作还是条件上是一个品味问题。在这种情况下,作者选择强调行动。
The author wanted to use the if at the end, but it has to be at the end of one statement not many. A
do {}
is one statement, so that will work.Personally, I would use an if statement, but it is a matter of taste whether the emphasis should be on the action or the condition. In this case the author chose to emphasize the action.
因为在 Perl 中“有不止一种方法可以做到这一点”
Because in perl "There's more than one way to do it"