Perl:如何应对几个条件

gio*_*ano 0 perl if-statement

我想改变一个变量,但如果第一个条件为真,则分别跳转到if-block的末尾,什么都不做.这个伪代码显示了我想要的内容:

if ( $x =~ /^\d{4}$/ ) {  # first condition
    $x = $x;
} 
elsif ( cond2 ) {         # second condition
    do something with $x;
}
elsif ( cond3  ) {        # third condition
    do something with $x;
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢上面的代码,因为我发现将变量赋给自己很奇怪.避免这种自我分配的另一种解决方案是:

if ( $x !~ /^\d{4}$/ ) {
    if ( cond2 ) {            # second condition
        do something with $x;
    }
    elsif ( cond3  ) {        # third condition
        do something with $x;
    }
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢这段代码的是它是嵌套的(什么使它变得复杂).我想要这样的东西:

if ( $x =~ /^\d{4}$/ ) {  # first condition
    stop here and go to the end  of the if block (END)
} 
elsif ( cond2 ) {         # second condition
    do something with $x;
}
elsif ( cond3  ) {        # third condition
    do something with $x;
} (END)
Run Code Online (Sandbox Code Playgroud)

我知道,有命令,最后未来,但我了解这些命令它们适用于失控的循环.

知道如何为这个问题编写一个简单的好代码吗?

谢谢你的任何提示.

Gre*_*ade 5

你错了if-else是如何工作的.

你写的地方

if ( $x =~ /^\d{4}$/ ) {  # first condition
    stop here and go to the end  of the if block (END)
Run Code Online (Sandbox Code Playgroud)

......这正是没有发生.

这(你写的):

if ( $x =~ /^\d{4}$/ ) {  # first condition
    $x = $x;
} 
elsif ( cond2 ) {         # second condition
    do something with $x;
}
elsif ( cond3  ) {        # third condition
    do something with $x;
}
Run Code Online (Sandbox Code Playgroud)

与此相同

if ( $x =~ /^\d{4}$/ ) {  # first condition
    # do nothing
} 
elsif ( cond2 ) {         # second condition
    do something with $x;
}
elsif ( cond3  ) {        # third condition
    do something with $x;
}
Run Code Online (Sandbox Code Playgroud)

当你理解这一点时,你想要的东西可能看起来更明显.