Perl 编程:避免“聪明”代码,追求高效与可维护性
1. 避免“聪明”代码
在编程中,我们常常会陷入追求“聪明”代码的陷阱。例如,下面这段代码用于读取每月结果并计算半年移动平均值:
my @cyclic_buffer;
while (my $next_val = prompt 'Next: ') {
# Saving them in a six - month cyclic buffer...
$cyclic_buffer[next_index( )] = $next_val;
# And printing the moving average each month...
print 'Half - yearly moving average: ',
sum(@cyclic_buffer)/@cyclic_buffer, "\n";
}
而像 $optimal_result = [$result1=>$result2]->[$result2<=$result1]; 这样的代码,虽然语法对称很优雅,但理解和维护起来却像是一场噩梦。它的工作原理是:
1. 第一个方括号 [$result1=>$result2] 创建一个包含两个结果的匿名数组。
2. 第二个方括号通过 $result2<=$result1 的比较结果作为索引来选择元素。如果 $result2 不大于 $result
超级会员免费看
订阅专栏 解锁全文
125

被折叠的 条评论
为什么被折叠?



