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?
Yes, 1 is treated as true, so the block after if (1) is always executed. The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean context. All other values are true.
if(1) means that the condition inside “if” is always true. The statements inside the if block will always execute.
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.
One difference is that do { ... }
returns a value whereas an if statement doesn't (although see the comments below.)
E.g.:
my $x = 3;
my $z = do { warn "in the do block"; 10 } if $x == 3;
You can accomplish almost the same thing with the ternary operator, although you can't sequence statements inside the branches of the ternary operator.
To me, it seems like a way to emphasize the code inside the if
more than the if
condition itself.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With