繁体   English   中英

Perl 3种条件的衬垫

[英]Perl One liner for 3 conditions

我有这个

if($x<10){                                  
    print "child";
}elseif($x>10 && $x<18){
    print "teenage"
}else{
    print "old"
}

我想放入一个perl衬垫,我该怎么做,请帮助我

您可以使用条件运算符。 您还需要只能说print一次-我也要去改变周围的环境,因为10是既不>10 ,也不<10 ,但你的代码认为10old

print $x<10 ? 'child' : $x<18 ? 'teenage' : 'old';
for my $x ( 5, 15, 55 ) {
    print "$x is ";
    print (($x<10) ? 'child' : ($x>10 && $x<18) ? 'teenage' : 'old');
    print "\n";
}

Perl中的条件运算符

您正在寻找条件运算符 (一种三元运算符,它是速记if语句的形式,而不是Perl特定的):

print $age < 10 ? "child" : $age < 18 ? "teenage" : "old";

另外,您的代码会将10视为旧的,因为它既不小于也不大于10,所以我将函数切换为我认为您想要的功能。

重用代码

您可以将其转换为子例程以方便重用:

sub determineAgeGroup {
    my $age = $_[0];
    return $age < 10 ? "a child" : $age < 18 ? "a teenager" : "old";
}

my @ages = (5,10,15,20);

foreach my $age (@ages) {
    print "If you're $age you're " . determineAgeGroup($age) . "\n";
}

输出为:

If you're 5 you're a child
If you're 10 you're a teenager
If you're 15 you're a teenager
If you're 20 you're old

链接到工作演示

不知道为什么要这么做,但这应该可行:

print (($x<10)?("child"):(($x>10 && $x<18)?("teenage"):("old")))

但是,仅仅因为它很短并不意味着它比原始的要好-比较支持/调试这两个选项的难度。

如果您只是在玩耍,还可以在适当的数组中定义字符串,并对$x的值进行一些数学运算以获得有效的数组条目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM