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
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
for my $x ( 5, 15, 55 ) {
print "$x is ";
print (($x<10) ? 'child' : ($x>10 && $x<18) ? 'teenage' : 'old');
print "\n";
}
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';
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.
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):
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:
Output to this is:
Link to working demo.