while(1){......}的使用最常构造

Ani*_*nil 2 perl

这是我的代码..

while (1) {
    do_stuff;
    do_some_checks;
    do {  warn error 1; last }  if not OK;

    do_more_stuff;
    do_some_checks;
    do {  warn error 2; last }  if not OK;

    do_even_more_stuff;
    do_some_checks;
    do {  warn error 3; last }  if not OK;

    ...
    #finally
    last;
}
Run Code Online (Sandbox Code Playgroud)

我比它更喜欢它:

do_stuff;
do_some_checks;
if (!OK) {
    warn error 1;
} else {
    do_more_stuff;
    do_some_checks;
    if (!OK) {
        warn error 2;
    } else {
       do_even_more_stuff;
       do_some_checks;
       if (!OK) {
           ...
       }
       # finally
       success!    
    }
}
Run Code Online (Sandbox Code Playgroud)

每次都会遇到我唯一的事情,虽然使用这个结构有时我忘记添加最终结果last,导致无限循环.但是这一系列的检查和早期保释模式在我的代码中经常发生,构造很快成为第二天性.

任何人都有相同的习惯,或者使用一些替代方案会有所帮助.

提前致谢.

Kon*_*rak 7

哇,你在那里完全滥用了.虽然是循环,但你不是循环.我明白你想要什么,但为什么不用一个子?

##
# This sub does three things:
# thing1,
# thing2, 
# thing3
sub do_three_things {   
 do_stuff;   
 do_some_checks;  
 do {  warn error 1; return }  if not OK;  

 do_more_stuff;  
 do_some_checks;   
 do {  warn error 2; return }  if not OK;  

 do_even_more_stuff;  
 do_some_checks;
 do {  warn error 3; return }  if not OK; 

   ...
#finally   
 return; #if you forget this return, the sub will end anyway.
}

do_three_things(); # Call the sub
Run Code Online (Sandbox Code Playgroud)

子的优点:

  • 更好的代码划分
  • 范围较小

编辑:正如Hachi所说,你甚至不需要一个sub,只是一个块也适用last.但是,我自己更喜欢sub,因此您可以更清楚地分离事物,从而可以更轻松地进行测试和/或代码重用.