我应该避免在Perl中嵌套if语句吗?

Isa*_*rke 5 perl coding-style nested

我正在做一些Perl并且看到我的嵌套"if"语句让我发疯.我设法在另一部分中使用防护块来减少其中一些,但我被困在这里.

您认为我可以保留代码,还是有一种"正确"的方式来重构以下内容?(我也承认对Perl来说比较新)

这实际上是一个子程序,要求用户输入列表的每个参数(外部文件).$ [3]是匹配模式,$ [2]是所考虑参数的默认值(如果没有则为NULL),$ _ [1]指定它是否是必需的.'next'语句引用下一个参数read(while循环).

在每个人的帮助下(谢谢!),这是最新版本.

100         if ( $input ne '' && ( $input !~ $match || $input =~ /'.+'/ ) ) {
101             print "! Format not respected. Match : /$match/ (without \' \')\n";
102             next;
103         }
104         if ( $input eq '' ) {
105             if ( $default eq 'NULL' ) {
106                 if ( $manda eq 'y' ) {
107                     print "! Mandatory parameter not filled in\n";
108                     next;
109                 }
110                 print "+ Ignoring parameter.\n";
111                 $input = '';
112             }
113             else {
114                 print "+ Using default value\n";
115                 $input = $default;
116             }
117         }
Run Code Online (Sandbox Code Playgroud)
 98        if($input eq ''){
 99             if($_[2] eq 'NULL'){
100                 if($_[1] eq 'y'){
101                     print "! Mandatory parameter not filled in\n";
102                     next;
103                 }
104                 else{
105                     print "+ Ignoring parameter.\n";
106                     $input = '';
107                 }
108             }
109             else{
110                 print "+ Using default value\n";
111                 $input = $_[2];
112             }
113         }
114         elsif($input !~ $_[3] || $input =~ /'.+'/){
115                 print "! Format not respected. Match : /$_[3]/ (without \' \')\n"; 
116                 next;
117             }
118         }
Run Code Online (Sandbox Code Playgroud)

ire*_*ses 10

这是一个稍微更易读的混沌答案版本:

# Set sane variable names...
my ($is_required, $default, $pattern) = @_

# Convert the external string convention for simpler evaluation...
$default = undef if $default eq 'NULL'

# Refuse problematic input before going any further...
if ($input ne '' && $input !~ $pattern || $input =~ /'.+'/) {
    print "! Format not respected. Match : /$pattern/ (without \' \')\n"; 
    next;
}


# If there was no input string...
if($input eq '') {

    # Set the default, if one was provided...
    if( $default ) {
        print "+ Using default value\n";
        $input = $default;
    } 
    # otherwise, complain if a default was required...
    else {
        if( $is_required eq 'y' ){
            print "! Mandatory parameter not filled in\n";
            next;
        }
        print "+ Ignoring parameter (no input or default provided).\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

关键点是:

  • 你不需要别人,如果你是退出当前环下一个
  • 应首先处理特殊情况
  • 使用命名变量可以极大地提高可读性