我应该使用Perl的条件吗? :作为switch/case语句的操作符,而不
Perl拥有
conditional运算符,与
C’s conditional operator相同。
要刷新,C和Perl中的条件运算符是: (test) ? (if test was true) : (if test was false) 如果使用左值,则可以通过一个操作进行分配和测试: my $x= $n==0 ? "n is 0" : "n is not 0"; 我正在A neat way to express multi-clause if statements in C-based languages阅读Igor Ostrovsky的博客,并意识到这在Perl中确实是一个“整洁的方式”。 例如:(编辑:使用Jonathan Leffler更易读的形式…) # ternary conditional form of if / elsif construct: my $s= $n == 0 ? "$n ain't squawt" : $n == 1 ? "$n is not a lot" : $n < 100 ? "$n is more than 1..." : $n < 1000 ? "$n is in triple digits" : "Wow! $n is thousands!" ; #default 其中读取的LOT比Perl中写的更容易: # Perl form,not using Switch or given / when my $t = do { if ($n == 0) { "$n ain't squawt" } elsif ($n == 1) { "$n is not a lot" } elsif ($n < 100) { "$n is more than 1..." } elsif ($n < 1000) { "$n is in triple digits" } else { "Wow! $n is thousands!" } }; 这里有什么问题吗?为什么我不会用这种方式写一个扩展的条件形式,而不是使用if(something){this} elsif(something){that}? 条件运算符有right associativity and low precedence.所以: a ? b : c ? d : e ? f : g 被解释为: a ? b : (c ? d : (e ? f : g)) 如果您的测试使用低于优先级的少数操作符之一,则可能需要括号:。你也可以用我认为的大括号把块放在表单中。 我知道已经弃用的Switch或Perl 5.10的给定/何时结构,我不是在寻找使用它们的建议。 这些是我的问题: >您是否看过Perl中使用的这种语法?**我没有看到,并不是在perlop或perlsyn中作为交替的替代方法。 ——–编辑 – 我接受了乔纳森·莱夫勒的回答,因为他指出我在Perl Best Practices。相关部分是6.17表格三元。这让我进一步调查使用。 (如果您使用Google Perl表格三元组,则可以看到其他评论。) 康威的两个例子是: my $salute; if ($name eq $EMPTY_STR) { $salute = 'Dear Customer'; } elsif ($name =~ m/A ((?:Sir|Dame) s+ S+)/xms) { $salute = "Dear $1"; } elsif ($name =~ m/([^n]*),s+ Ph[.]?D z/xms) { $sa1ute = "Dear Dr $1"; } else { $salute = "Dear $name"; } VS: # Name format... # Salutation... my $salute = $name eq $EMPTY_STR ? 'Dear Customer' : $name =~ m/ A((?:Sir|Dame) s+ S+) /xms ? "Dear $1" : $name =~ m/ (.*),s+ Ph[.]?D z /xms ? "Dear Dr $1" : "Dear $name" ; 我的结论是: > Conway的?:例子比if / elsif格式更可读,更简单,但是我可以看到这个表单怎么会很难理解。 解决方法
为条件运算符显示的布局很难阅读。
这更像是我所说的 Perl Best Practices推荐: my $s = $n == 0 ? "$n ain't squawt" : $n == 1 ? "$n is not a lot" : $n < 100 ? "$n is more than 1..." : $n < 1000 ? "$n is in triple digits" : "Wow! $n is thousands!"; # default... 而且,有时更好地使用更简洁的符号,如果符号也是如此: if ($n == 0) { $t = "$n ain't squawt"; } elsif ($n == 1) { $t = "$n is not a lot"; } elsif ($n < 100) { $t = "$n is more than 1..."; } elsif ($n < 1000) { $t = "$n is in triple digits"; } else { $t = "Wow! $n is thousands!" ; } 这些重新格式化都强调了代码的各个部分的相似性,使其更容易阅读和理解。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |