When "if" is written at the end of a line in perl, what is its scope

this question really comes from using threads. We know that in perl threads we have a function called blocking, and according to cpan http://perldoc.perl.org/threads/shared.html : blocking blocks the control blocking of the variable until the blocking is out of scope. It’s good that if we write something like this:

1 sub foo{ 2 lock($obj) if threads::shared::is_shared($obj); #equivalent to if(threads::shared::is_shared($obj)) {lock($obj);} ? 3 ... rest of the code 4 ... more code 5 } 

so that the lock area is from line 2 to line 4 or only line 2? if the expression "if" adds a block to it, then the lock ($ obj) can only be line 2, see my #comments


the answer is actually the question, but I want to add some conclusions:

I found that no matter how you write:

 lock($ojb) if threads::shared::is_shared($obj); 

or

 if (threads::shared::is_shared($obj)) { lock($ojb); } 

the blocking area is the same - the whole function foo ().

+4
source share
3 answers

The if modifier does not place an implicit block around the statement to which it refers. Thus, the lock area (if applicable) is the rest of your routine.

+7
source

Based on the results of the experiment, I found that no matter how you write:

 lock($ojb) if threads::shared::is_shared($obj); 

or

 if (threads::shared::is_shared($obj)) { lock($ojb); } 

the blocking area is the same - the whole function foo ().

0
source

From the document itself that you linked in the question:

  my $var :shared; { lock($var); # $var is locked from here to the end of the block ... } # $var is now unlocked 

Thus, the lock continues until the end of the block.

-2
source

All Articles