簡體   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