Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use a "do {} if" block in Perl?

Tags:

syntax

perl

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?

like image 876
Mark McDonald Avatar asked Nov 15 '11 03:11

Mark McDonald


People also ask

Is if 1 always true?

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.

What is the meaning of if 1?

if(1) means that the condition inside “if” is always true. The statements inside the if block will always execute.


4 Answers

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.

like image 56
Keith Irwin Avatar answered Oct 02 '22 15:10

Keith Irwin


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.

like image 44
ErikR Avatar answered Oct 02 '22 15:10

ErikR


To me, it seems like a way to emphasize the code inside the if more than the if condition itself.

like image 37
Jordão Avatar answered Oct 02 '22 16:10

Jordão


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.

like image 35
Bill Ruppert Avatar answered Oct 02 '22 15:10

Bill Ruppert