条件(三元)运算符
减少Perl代码冗余的一种方法是将if-else语句替换为条件运算符表达式。条件运算符(也称为三元运算符)的形式为:逻辑测试 ? 为真时的值 : 为假时的值。
让我们将标准的Perl if-else转换为条件运算符等价物,使用一个虚构的子程序。首先,这是if-else语句:
sub calculate_salary {
my $hours = shift;
my $salary;
if ($hours > 40) {
$salary = get_overtime_wage($hours);
}
else {
$salary = get_normal_wage($hours);
}
return $salary;
}
这是使用条件运算符的相同语句
sub calculate_salary {
my $hours = shift;
return $hours > 40 ? get_overtime_wage($hours) : get_normal_wage($hours);
}
希望这个例子能展示使用条件运算符如何缩短并简化Perl代码。有关详细信息,请参阅官方文档。
本文最初发布于PerlTricks.com。
标签
反馈
这篇文章有什么问题吗?请通过在GitHub上打开问题或拉取请求来帮助我们。
LATEST COMMUNITY ARTICLES
- More commenting... maybe?
github.polettix.it - Perl Weekly Challenge 121: Invert Bit
blogs.perl.org - Web nostalgia: MojoX::Mechanize
github.polettix.it - On the eve of CPAN Testers
blogs.perl.org - PWC121 - The Travelling Salesman
github.polettix.it - PWC121 - Invert Bit
github.polettix.it - Floyd-Warshall algorithm implementations
github.polettix.it - Perl Weekly Challenge 120: Swap Odd/Even Bits and Clock Angle
blogs.perl.org - How I Uploaded a CPAN Module
blogs.perl.org - App::Easer released on CPAN
github.polettix.it