Perl Ternary Operator

Perl Ternary Operator
Perl Ternary Operator

You are probably familiar with writing if / else statements with perl. In this tutorial we will cover some ways you can use the Perl Ternary Operator to shorten your if / else statements into a single line of code. Saving you a bunch of keystrokes and making your code more efficient.

The Perl Turnary Operator, what is it?

First what is a Perl Turnary Operator? A Perl Turnary Operator is simply an Operator that takes 3 arguments. For example: 1) IF 2)DO THIS IF TRUE 3) DO THIS IF FALSE.

As you will see in the below examples, the Perl Turnary Operator is a powerful way to make your code more efficient.

Code Examples

You are probably familiar with the following block of example code. It is your standard if / else statement in perl.


if (condition) {
doThis_if_condition_true;
} else {
doThis_if_condition_false;
}

Another working example might look something like this:


my $input = shift;
if ($input =~ /A/) {
print "Macthed A\n";
} else {
print "No Match for A\n";
}

You can simplify this block of code by using a turnary. As you write it out, separate the arguments with “?” and “:”. For example:


condition ? doThis_if_condition_true : doThis_if_condition_false;
Or, using our working example it would look like this:

my $input = shift;
if ($input =~ /A/) ? print "Macthed A\n" : print "No Match for A\n";

Conclusion

The Perl Turnary Operator is a powerful tool and great way to shorten your code. You can get much more creative than the above examples. This is simply a brief tutorial on Perl Turnary Operators. Experiment with the possibilities, have fun, and enjoy your coding!

-Tutor


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *