Perl One liner for 3 conditions

1.4k Views Asked by At

I have this

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

I want to put in a perl one liner how could i do this please help me

4

There are 4 best solutions below

1
On BEST ANSWER

Conditional operator in Perl

You're looking for the conditional operator (a form of ternary operator which acts as a shorthand if-statement, not Perl-specific):

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

Also, your code treats 10 as old, as it's neither less than nor greater than 10, so I've switched the function to what I think you wanted it to do.

Reusing the code

You can turn this into a subroutine for easy reuse:

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";
}

Output to this is:

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

Link to working demo.

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

You may use the conditional operator. You also need only say print once - and I'm also going to change your conditions around, because 10 is neither >10 nor <10, but your code thinks 10 is old.

print $x<10 ? 'child' : $x<18 ? 'teenage' : 'old';
0
On

No idea why you'd want to but this should work:

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

But just because it's short doesn't mean it's better than the original -- compare the difficulty in supporting/debugging the two options.

If you're just playing around the you could also define the strings in an appropriate array and do some maths on the value of $x to get a valid array entry.