【发布时间】:2013-03-21 01:57:51
【问题描述】:
我正在做一些 Perl,看到我嵌套的“if”语句让我发疯。我设法在另一部分用防护块减少了其中一些,但我被困在这里。
您认为我可以将代码保持原样,还是有一种“正确”的方式来重构以下代码? (我也承认对 Perl 比较陌生)
这实际上是一个子程序,要求用户输入列表(外部文件)的每个参数。 $[3] 是匹配模式,$[2] 是所考虑参数的默认值(如果没有,则为 NULL),$_[1] 指定它是否是强制性的。 'next' 语句是指读取的下一个参数(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 }
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 }
【问题讨论】:
-
究竟是什么让您对那些嵌套的 if 感到抓狂?
-
我不知道,我只是觉得还有另一种写法……
标签: perl coding-style nested